Update to master

This commit is contained in:
Amish Shah
2017-10-29 13:50:49 +00:00
35 changed files with 213 additions and 129 deletions

View File

@@ -10,8 +10,7 @@
<a href="https://www.npmjs.com/package/discord.js"><img src="https://img.shields.io/npm/dt/discord.js.svg?maxAge=3600" alt="NPM downloads" /></a> <a href="https://www.npmjs.com/package/discord.js"><img src="https://img.shields.io/npm/dt/discord.js.svg?maxAge=3600" alt="NPM downloads" /></a>
<a href="https://travis-ci.org/hydrabolt/discord.js"><img src="https://travis-ci.org/hydrabolt/discord.js.svg" alt="Build status" /></a> <a href="https://travis-ci.org/hydrabolt/discord.js"><img src="https://travis-ci.org/hydrabolt/discord.js.svg" alt="Build status" /></a>
<a href="https://david-dm.org/hydrabolt/discord.js"><img src="https://img.shields.io/david/hydrabolt/discord.js.svg?maxAge=3600" alt="Dependencies" /></a> <a href="https://david-dm.org/hydrabolt/discord.js"><img src="https://img.shields.io/david/hydrabolt/discord.js.svg?maxAge=3600" alt="Dependencies" /></a>
<a href="https://www.patreon.com/discordjs"><img <a href="https://www.patreon.com/discordjs"><img src="https://img.shields.io/badge/donate-patreon-F96854.svg" alt="Patreon" /></a>
src="https://img.shields.io/badge/donate-patreon-F96854.svg" alt="Patreon" /></a>
</p> </p>
<p> <p>
<a href="https://nodei.co/npm/discord.js/"><img src="https://nodei.co/npm/discord.js.png?downloads=true&stars=true" alt="NPM info" /></a> <a href="https://nodei.co/npm/discord.js/"><img src="https://nodei.co/npm/discord.js.png?downloads=true&stars=true" alt="NPM info" /></a>
@@ -31,9 +30,9 @@ discord.js is a powerful [node.js](https://nodejs.org) module that allows you to
**Node.js 8.0.0 or newer is required.** **Node.js 8.0.0 or newer is required.**
Ignore any warnings about unmet peer dependencies, as they're all optional. Ignore any warnings about unmet peer dependencies, as they're all optional.
Without voice support: `npm install discord.js --save` Without voice support: `npm i discord.js`
With voice support ([node-opus](https://www.npmjs.com/package/node-opus)): `npm install discord.js node-opus --save` With voice support ([node-opus](https://www.npmjs.com/package/node-opus)): `npm i discord.js node-opus`
With voice support ([opusscript](https://www.npmjs.com/package/opusscript)): `npm install discord.js opusscript --save` With voice support ([opusscript](https://www.npmjs.com/package/opusscript)): `npm i discord.js opusscript`
### Audio engines ### Audio engines
The preferred audio engine is node-opus, as it performs significantly better than opusscript. When both are available, discord.js will automatically choose node-opus. The preferred audio engine is node-opus, as it performs significantly better than opusscript. When both are available, discord.js will automatically choose node-opus.
@@ -41,13 +40,13 @@ Using opusscript is only recommended for development environments where node-opu
For production bots, using node-opus should be considered a necessity, especially if they're going to be running on multiple servers. For production bots, using node-opus should be considered a necessity, especially if they're going to be running on multiple servers.
### Optional packages ### Optional packages
- [zlib-sync](https://www.npmjs.com/package/zlib-sync) for significantly faster WebSocket data inflation (`npm install zlib-sync`) - [zlib-sync](https://www.npmjs.com/package/zlib-sync) for significantly faster WebSocket data inflation (`npm i zlib-sync`)
- [bufferutil](https://www.npmjs.com/package/bufferutil) to greatly speed up the WebSocket when *not* using uws (`npm install bufferutil --save`) - [erlpack](https://github.com/discordapp/erlpack) for significantly faster WebSocket data (de)serialisation (`npm i discordapp/erlpack`)
- [erlpack](https://github.com/hammerandchisel/erlpack) for significantly faster WebSocket data (de)serialisation (`npm install discordapp/erlpack --save`)
- One of the following packages can be installed for faster voice packet encryption and decryption: - One of the following packages can be installed for faster voice packet encryption and decryption:
- [sodium](https://www.npmjs.com/package/sodium) (`npm install sodium --save`) - [sodium](https://www.npmjs.com/package/sodium) (`npm i sodium`)
- [libsodium.js](https://www.npmjs.com/package/libsodium-wrappers) (`npm install libsodium-wrappers --save`) - [libsodium.js](https://www.npmjs.com/package/libsodium-wrappers) (`npm i libsodium-wrappers`)
- [uws](https://www.npmjs.com/package/uws) for a much faster WebSocket connection (`npm install uws --save`) - [uws](https://www.npmjs.com/package/uws) for a much faster WebSocket connection (`npm i uws`)
- [bufferutil](https://www.npmjs.com/package/bufferutil) for a much faster WebSocket connection when *not* using uws (`npm i bufferutil`)
## Example usage ## Example usage
```js ```js
@@ -70,11 +69,14 @@ client.login('your token');
## Links ## Links
* [Website](https://discord.js.org/) ([source](https://github.com/hydrabolt/discord.js-site)) * [Website](https://discord.js.org/) ([source](https://github.com/hydrabolt/discord.js-site))
* [Documentation](https://discord.js.org/#/docs) * [Documentation](https://discord.js.org/#/docs)
* [Discord.js server](https://discord.gg/bRCvFy9) * [Discord.js Discord server](https://discord.gg/bRCvFy9)
* [Discord API server](https://discord.gg/rV4BwdK) * [Discord API Discord server](https://discord.gg/discord-api)
* [GitHub](https://github.com/hydrabolt/discord.js) * [GitHub](https://github.com/hydrabolt/discord.js)
* [NPM](https://www.npmjs.com/package/discord.js) * [NPM](https://www.npmjs.com/package/discord.js)
* [Related libraries](https://discordapi.com/unofficial/libs.html) (see also [discord-rpc](https://www.npmjs.com/package/discord-rpc)) * [Related libraries](https://discordapi.com/unofficial/libs.html)
### Extensions
* [discord-rpc](https://www.npmjs.com/package/discord-rpc) ([github](https://github.com/devsnek/discord-rpc))
## Contributing ## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the

View File

@@ -22,6 +22,7 @@ class ClientManager {
/** /**
* The status of the client * The status of the client
* @readonly
* @type {number} * @type {number}
*/ */
get status() { get status() {

View File

@@ -272,7 +272,7 @@ class WebSocketConnection extends EventEmitter {
try { try {
const packet = WebSocket.unpack(this.inflate.result); const packet = WebSocket.unpack(this.inflate.result);
this.onPacket(packet); this.onPacket(packet);
if (this.client.listenerCount('raw')) this.client.emit('raw', data); if (this.client.listenerCount('raw')) this.client.emit('raw', packet);
} catch (err) { } catch (err) {
this.client.emit('debug', err); this.client.emit('debug', err);
} }

View File

@@ -15,7 +15,6 @@ module.exports = {
DataResolver: require('./util/DataResolver'), DataResolver: require('./util/DataResolver'),
DataStore: require('./stores/DataStore'), DataStore: require('./stores/DataStore'),
DiscordAPIError: require('./rest/DiscordAPIError'), DiscordAPIError: require('./rest/DiscordAPIError'),
EvaluatedPermissions: require('./util/Permissions'),
Permissions: require('./util/Permissions'), Permissions: require('./util/Permissions'),
Snowflake: require('./util/Snowflake'), Snowflake: require('./util/Snowflake'),
SnowflakeUtil: require('./util/Snowflake'), SnowflakeUtil: require('./util/Snowflake'),
@@ -23,15 +22,32 @@ module.exports = {
util: Util, util: Util,
version: require('../package.json').version, version: require('../package.json').version,
// Stores
ChannelStore: require('./stores/ChannelStore'),
ClientPresenceStore: require('./stores/ClientPresenceStore'),
EmojiStore: require('./stores/EmojiStore'),
GuildChannelStore: require('./stores/GuildChannelStore'),
GuildMemberStore: require('./stores/GuildMemberStore'),
GuildStore: require('./stores/GuildStore'),
MessageStore: require('./stores/MessageStore'),
PresenceStore: require('./stores/PresenceStore'),
RoleStore: require('./stores/RoleStore'),
UserStore: require('./stores/UserStore'),
// Shortcuts to Util methods // Shortcuts to Util methods
escapeMarkdown: Util.escapeMarkdown, escapeMarkdown: Util.escapeMarkdown,
fetchRecommendedShards: Util.fetchRecommendedShards, fetchRecommendedShards: Util.fetchRecommendedShards,
splitMessage: Util.splitMessage, splitMessage: Util.splitMessage,
// Structures // Structures
Base: require('./structures/Base'),
Activity: require('./structures/Presence').Activity, Activity: require('./structures/Presence').Activity,
CategoryChannel: require('./structures/CategoryChannel'),
Channel: require('./structures/Channel'), Channel: require('./structures/Channel'),
ClientApplication: require('./structures/ClientApplication'),
ClientUser: require('./structures/ClientUser'), ClientUser: require('./structures/ClientUser'),
ClientUserChannelOverride: require('./structures/ClientUserChannelOverride'),
ClientUserGuildSettings: require('./structures/ClientUserGuildSettings'),
ClientUserSettings: require('./structures/ClientUserSettings'), ClientUserSettings: require('./structures/ClientUserSettings'),
Collector: require('./structures/interfaces/Collector'), Collector: require('./structures/interfaces/Collector'),
DMChannel: require('./structures/DMChannel'), DMChannel: require('./structures/DMChannel'),
@@ -48,15 +64,17 @@ module.exports = {
MessageEmbed: require('./structures/MessageEmbed'), MessageEmbed: require('./structures/MessageEmbed'),
MessageMentions: require('./structures/MessageMentions'), MessageMentions: require('./structures/MessageMentions'),
MessageReaction: require('./structures/MessageReaction'), MessageReaction: require('./structures/MessageReaction'),
ClientApplication: require('./structures/ClientApplication'),
PermissionOverwrites: require('./structures/PermissionOverwrites'), PermissionOverwrites: require('./structures/PermissionOverwrites'),
Presence: require('./structures/Presence').Presence, Presence: require('./structures/Presence').Presence,
ReactionEmoji: require('./structures/ReactionEmoji'),
ReactionCollector: require('./structures/ReactionCollector'), ReactionCollector: require('./structures/ReactionCollector'),
ReactionEmoji: require('./structures/ReactionEmoji'),
RichPresenceAssets: require('./structures/Presence').RichPresenceAssets,
Role: require('./structures/Role'), Role: require('./structures/Role'),
TextChannel: require('./structures/TextChannel'), TextChannel: require('./structures/TextChannel'),
User: require('./structures/User'), User: require('./structures/User'),
UserConnection: require('./structures/UserConnection'),
VoiceChannel: require('./structures/VoiceChannel'), VoiceChannel: require('./structures/VoiceChannel'),
VoiceRegion: require('./structures/VoiceRegion'),
Webhook: require('./structures/Webhook'), Webhook: require('./structures/Webhook'),
WebSocket: require('./WebSocket'), WebSocket: require('./WebSocket'),

View File

@@ -12,12 +12,22 @@ class RESTManager {
this.globallyRateLimited = false; this.globallyRateLimited = false;
this.tokenPrefix = tokenPrefix; this.tokenPrefix = tokenPrefix;
this.versioned = true; this.versioned = true;
this.timeDifferences = [];
} }
get api() { get api() {
return routeBuilder(this); return routeBuilder(this);
} }
get timeDifference() {
return Math.round(this.timeDifferences.reduce((a, b) => a + b, 0) / this.timeDifferences.length);
}
set timeDifference(ms) {
this.timeDifferences.unshift(ms);
if (this.timeDifferences.length > 5) this.timeDifferences.length = 5;
}
getAuth() { getAuth() {
const token = this.client.token || this.client.accessToken; const token = this.client.token || this.client.accessToken;
const prefixed = !!this.client.application || (this.client.user && this.client.user.bot); const prefixed = !!this.client.application || (this.client.user && this.client.user.bot);

View File

@@ -9,7 +9,6 @@ class RequestHandler {
this.limit = Infinity; this.limit = Infinity;
this.resetTime = null; this.resetTime = null;
this.remaining = 1; this.remaining = 1;
this.timeDifference = 0;
this.queue = []; this.queue = [];
} }
@@ -32,7 +31,7 @@ class RequestHandler {
const finish = timeout => { const finish = timeout => {
if (timeout || this.limited) { if (timeout || this.limited) {
if (!timeout) { if (!timeout) {
timeout = this.resetTime - Date.now() + this.timeDifference + this.client.options.restTimeOffset; timeout = this.resetTime - Date.now() + this.manager.timeDifference + this.client.options.restTimeOffset;
} }
// eslint-disable-next-line prefer-promise-reject-errors // eslint-disable-next-line prefer-promise-reject-errors
reject({ timeout }); reject({ timeout });
@@ -50,7 +49,7 @@ class RequestHandler {
this.client.emit(RATE_LIMIT, { this.client.emit(RATE_LIMIT, {
timeout, timeout,
limit: this.limit, limit: this.limit,
timeDifference: this.timeDifference, timeDifference: this.manager.timeDifference,
method: item.request.method, method: item.request.method,
path: item.request.path, path: item.request.path,
route: item.request.route, route: item.request.route,
@@ -66,7 +65,7 @@ class RequestHandler {
this.limit = Number(res.headers['x-ratelimit-limit']); this.limit = Number(res.headers['x-ratelimit-limit']);
this.resetTime = Number(res.headers['x-ratelimit-reset']) * 1000; this.resetTime = Number(res.headers['x-ratelimit-reset']) * 1000;
this.remaining = Number(res.headers['x-ratelimit-remaining']); this.remaining = Number(res.headers['x-ratelimit-remaining']);
this.timeDifference = Date.now() - new Date(res.headers.date).getTime(); this.manager.timeDifference = Date.now() - new Date(res.headers.date).getTime();
} }
if (err) { if (err) {
if (err.status === 429) { if (err.status === 429) {

View File

@@ -95,7 +95,7 @@ class ChannelStore extends DataStore {
* @memberof ChannelStore * @memberof ChannelStore
* @instance * @instance
* @param {ChannelResolvable} channel The channel resolvable to resolve * @param {ChannelResolvable} channel The channel resolvable to resolve
* @returns {?string} * @returns {?Snowflake}
*/ */
} }

View File

@@ -37,7 +37,7 @@ class DataStore extends Collection {
/** /**
* Resolves a data entry to a instance ID. * Resolves a data entry to a instance ID.
* @param {string|Instance} idOrInstance The id or instance of something in this DataStore * @param {string|Instance} idOrInstance The id or instance of something in this DataStore
* @returns {?string} * @returns {?Snowflake}
*/ */
resolveID(idOrInstance) { resolveID(idOrInstance) {
if (idOrInstance instanceof this.holds) return idOrInstance.id; if (idOrInstance instanceof this.holds) return idOrInstance.id;

View File

@@ -38,7 +38,7 @@ class EmojiStore extends DataStore {
/** /**
* Resolves a EmojiResolvable to a Emoji ID string. * Resolves a EmojiResolvable to a Emoji ID string.
* @param {EmojiResolvable} emoji The Emoji resolvable to identify * @param {EmojiResolvable} emoji The Emoji resolvable to identify
* @returns {?string} * @returns {?Snowflake}
*/ */
resolveID(emoji) { resolveID(emoji) {
if (emoji instanceof ReactionEmoji) return emoji.id; if (emoji instanceof ReactionEmoji) return emoji.id;

View File

@@ -42,7 +42,7 @@ class GuildChannelStore extends DataStore {
* @memberof GuildChannelStore * @memberof GuildChannelStore
* @instance * @instance
* @param {GuildChannelResolvable} channel The GuildChannel resolvable to resolve * @param {GuildChannelResolvable} channel The GuildChannel resolvable to resolve
* @returns {?string} * @returns {?Snowflake}
*/ */
} }

View File

@@ -41,7 +41,7 @@ class GuildMemberStore extends DataStore {
/** /**
* Resolves a GuildMemberResolvable to an member ID string. * Resolves a GuildMemberResolvable to an member ID string.
* @param {GuildMemberResolvable} member The user that is part of the guild * @param {GuildMemberResolvable} member The user that is part of the guild
* @returns {?string} * @returns {?Snowflake}
*/ */
resolveID(member) { resolveID(member) {
const memberResolveable = super.resolveID(member); const memberResolveable = super.resolveID(member);

View File

@@ -33,7 +33,7 @@ class GuildStore extends DataStore {
* @memberof GuildStore * @memberof GuildStore
* @instance * @instance
* @param {GuildResolvable} guild The guild resolvable to identify * @param {GuildResolvable} guild The guild resolvable to identify
* @returns {?string} * @returns {?Snowflake}
*/ */
} }

View File

@@ -112,7 +112,7 @@ class MessageStore extends DataStore {
* @memberof MessageStore * @memberof MessageStore
* @instance * @instance
* @param {MessageResolvable} message The message resolvable to resolve * @param {MessageResolvable} message The message resolvable to resolve
* @returns {?string} * @returns {?Snowflake}
*/ */
} }

View File

@@ -39,7 +39,7 @@ class PresenceStore extends DataStore {
/** /**
* Resolves a PresenceResolvable to a Presence ID string. * Resolves a PresenceResolvable to a Presence ID string.
* @param {PresenceResolvable} presence The presence resolvable to resolve * @param {PresenceResolvable} presence The presence resolvable to resolve
* @returns {?string} * @returns {?Snowflake}
*/ */
resolveID(presence) { resolveID(presence) {
const presenceResolveable = super.resolveID(presence); const presenceResolveable = super.resolveID(presence);

View File

@@ -38,7 +38,7 @@ class ReactionStore extends DataStore {
* @memberof ReactionStore * @memberof ReactionStore
* @instance * @instance
* @param {MessageReactionResolvable} role The role resolvable to resolve * @param {MessageReactionResolvable} role The role resolvable to resolve
* @returns {?string} * @returns {?Snowflake}
*/ */
} }

View File

@@ -38,7 +38,7 @@ class RoleStore extends DataStore {
* @memberof RoleStore * @memberof RoleStore
* @instance * @instance
* @param {RoleResolvable} role The role resolvable to resolve * @param {RoleResolvable} role The role resolvable to resolve
* @returns {?string} * @returns {?Snowflake}
*/ */
} }

View File

@@ -35,7 +35,7 @@ class UserStore extends DataStore {
/** /**
* Resolves a UserResolvable to a user ID string. * Resolves a UserResolvable to a user ID string.
* @param {UserResolvable} user The UserResolvable to identify * @param {UserResolvable} user The UserResolvable to identify
* @returns {?string} * @returns {?Snowflake}
*/ */
resolveID(user) { resolveID(user) {
if (user instanceof GuildMember) return user.user.id; if (user instanceof GuildMember) return user.user.id;

View File

@@ -177,7 +177,7 @@ class ClientApplication extends Base {
/** /**
* Resets the app's secret. * Resets the app's secret.
* <warn>This is only available when using a user account.</warn> * <warn>This is only available when using a user account.</warn>
* @returns {ClientApplication} * @returns {Promise<ClientApplication>}
*/ */
resetSecret() { resetSecret() {
return this.client.api.oauth2.applications[this.id].reset.post() return this.client.api.oauth2.applications[this.id].reset.post()
@@ -187,7 +187,7 @@ class ClientApplication extends Base {
/** /**
* Resets the app's bot token. * Resets the app's bot token.
* <warn>This is only available when using a user account.</warn> * <warn>This is only available when using a user account.</warn>
* @returns {ClientApplication} * @returns {Promise<ClientApplication>}
*/ */
resetToken() { resetToken() {
return this.client.api.oauth2.applications[this.id].bot.reset.post() return this.client.api.oauth2.applications[this.id].bot.reset.post()
@@ -195,8 +195,12 @@ class ClientApplication extends Base {
} }
/** /**
* When concatenated with a string, this automatically concatenates the app name rather than the app object. * When concatenated with a string, this automatically returns the application's name instead of the
* ClientApplication object.
* @returns {string} * @returns {string}
* @example
* // Logs: Application name: My App
* console.log(`Application name: ${application}`);
*/ */
toString() { toString() {
return this.name; return this.name;

View File

@@ -88,6 +88,8 @@ class ClientUser extends User {
this.guildSettings.set(settings.guild_id, new ClientUserGuildSettings(this.client, settings)); this.guildSettings.set(settings.guild_id, new ClientUserGuildSettings(this.client, settings));
} }
} }
if (data.token) this.client.token = data.token;
} }
/** /**

View File

@@ -27,9 +27,12 @@ class DMChannel extends Channel {
} }
/** /**
* When concatenated with a string, this automatically concatenates the recipient's mention instead of the * When concatenated with a string, this automatically returns the recipient's mention instead of the
* DM channel object. * DMChannel object.
* @returns {string} * @returns {string}
* @example
* // Logs: Hello from <@123456789012345678>!
* console.log(`Hello from ${channel}!`);
*/ */
toString() { toString() {
return this.recipient.toString(); return this.recipient.toString();

View File

@@ -190,7 +190,7 @@ class Emoji extends Base {
} }
/** /**
* When concatenated with a string, this automatically returns the emoji mention rather than the object. * When concatenated with a string, this automatically concatenates the emoji's mention instead of the Emoji object.
* @returns {string} * @returns {string}
* @example * @example
* // Send an emoji: * // Send an emoji:

View File

@@ -203,14 +203,12 @@ class GroupDMChannel extends Channel {
} }
/** /**
* When concatenated with a string, this automatically concatenates the channel's name instead of the Channel object. * When concatenated with a string, this automatically returns the channel's name instead of the
* GroupDMChannel object.
* @returns {string} * @returns {string}
* @example * @example
* // Logs: Hello from My Group DM! * // Logs: Hello from My Group DM!
* console.log(`Hello from ${channel}!`); * console.log(`Hello from ${channel}!`);
* @example
* // Logs: Hello from My Group DM!
* console.log(`Hello from ' + channel + '!');
*/ */
toString() { toString() {
return this.name; return this.name;

View File

@@ -115,7 +115,7 @@ class Guild extends Base {
/** /**
* An array of guild features * An array of guild features
* @type {Object[]} * @type {string[]}
*/ */
this.features = data.features; this.features = data.features;
@@ -401,7 +401,7 @@ class Guild extends Base {
} }
} }
/* /**
* The `@everyone` role of the guild * The `@everyone` role of the guild
* @type {Role} * @type {Role}
* @readonly * @readonly
@@ -802,7 +802,7 @@ class Guild extends Base {
/** /**
* Bans a user from the guild. * Bans a user from the guild.
* @param {UserResolvable} user The user to ban * @param {UserResolvable} user The user to ban
* @param {Object|number|string} [options] Ban options. If a number, the number of days to delete messages for, if a * @param {Object} [options] Ban options. If a number, the number of days to delete messages for, if a
* string, the ban reason. Supplying an object allows you to do both. * string, the ban reason. Supplying an object allows you to do both.
* @param {number} [options.days=0] Number of days of messages to delete * @param {number} [options.days=0] Number of days of messages to delete
* @param {string} [options.reason] Reason for banning * @param {string} [options.reason] Reason for banning
@@ -979,7 +979,7 @@ class Guild extends Base {
} }
/** /**
* Creates a new role in the guild with given information * Creates a new role in the guild with given information.
* <warn>The position will silently reset to 1 if an invalid one is provided, or none.</warn> * <warn>The position will silently reset to 1 if an invalid one is provided, or none.</warn>
* @param {Object} [options] Options * @param {Object} [options] Options
* @param {RoleData} [options.data] The data to update the role with * @param {RoleData} [options.data] The data to update the role with
@@ -1000,7 +1000,7 @@ class Guild extends Base {
* reason: 'we needed a role for Super Cool People', * reason: 'we needed a role for Super Cool People',
* }) * })
* .then(role => console.log(`Created role ${role}`)) * .then(role => console.log(`Created role ${role}`))
* .catch(console.error) * .catch(console.error);
*/ */
createRole({ data = {}, reason } = {}) { createRole({ data = {}, reason } = {}) {
if (data.color) data.color = Util.resolveColor(data.color); if (data.color) data.color = Util.resolveColor(data.color);
@@ -1123,14 +1123,11 @@ class Guild extends Base {
} }
/** /**
* When concatenated with a string, this automatically concatenates the guild's name instead of the guild object. * When concatenated with a string, this automatically returns the guild's name instead of the Guild object.
* @returns {string} * @returns {string}
* @example * @example
* // Logs: Hello from My Guild! * // Logs: Hello from My Guild!
* console.log(`Hello from ${guild}!`); * console.log(`Hello from ${guild}!`);
* @example
* // Logs: Hello from My Guild!
* console.log('Hello from ' + guild + '!');
*/ */
toString() { toString() {
return this.name; return this.name;

View File

@@ -2,6 +2,24 @@ const Collection = require('../util/Collection');
const Snowflake = require('../util/Snowflake'); const Snowflake = require('../util/Snowflake');
const Webhook = require('./Webhook'); const Webhook = require('./Webhook');
/**
* The target type of an entry, e.g. `GUILD`. Here are the available types:
* * GUILD
* * CHANNEL
* * USER
* * ROLE
* * INVITE
* * WEBHOOK
* * EMOJI
* * MESSAGE
* @typedef {string} AuditLogTargetType
*/
/**
* Key mirror of all available audit log targets.
* @name GuildAuditLogs.Targets
* @type {AuditLogTargetType}
*/
const Targets = { const Targets = {
ALL: 'ALL', ALL: 'ALL',
GUILD: 'GUILD', GUILD: 'GUILD',
@@ -15,6 +33,43 @@ const Targets = {
UNKNOWN: 'UNKNOWN', UNKNOWN: 'UNKNOWN',
}; };
/**
* The action of an entry. Here are the available actions:
* * ALL: null
* * GUILD_UPDATE: 1
* * CHANNEL_CREATE: 10
* * CHANNEL_UPDATE: 11
* * CHANNEL_DELETE: 12
* * CHANNEL_OVERWRITE_CREATE: 13
* * CHANNEL_OVERWRITE_UPDATE: 14
* * CHANNEL_OVERWRITE_DELETE: 15
* * MEMBER_KICK: 20
* * MEMBER_PRUNE: 21
* * MEMBER_BAN_ADD: 22
* * MEMBER_BAN_REMOVE: 23
* * MEMBER_UPDATE: 24
* * MEMBER_ROLE_UPDATE: 25
* * ROLE_CREATE: 30
* * ROLE_UPDATE: 31
* * ROLE_DELETE: 32
* * INVITE_CREATE: 40
* * INVITE_UPDATE: 41
* * INVITE_DELETE: 42
* * WEBHOOK_CREATE: 50
* * WEBHOOK_UPDATE: 51
* * WEBHOOK_DELETE: 50
* * EMOJI_CREATE: 60
* * EMOJI_UPDATE: 61
* * EMOJI_DELETE: 62
* * MESSAGE_DELETE: 72
* @typedef {?number|string} AuditLogAction
*/
/**
* All available actions keyed under their names to their numeric values.
* @name GuildAuditLogs.Actions
* @type {AuditLogAction}
*/
const Actions = { const Actions = {
ALL: null, ALL: null,
GUILD_UPDATE: 1, GUILD_UPDATE: 1,
@@ -85,20 +140,7 @@ class GuildAuditLogs {
} }
/** /**
* The target type of an entry, e.g. `GUILD`. Here are the available types: * The target of an entry. It can be one of:
* * GUILD
* * CHANNEL
* * USER
* * ROLE
* * INVITE
* * WEBHOOK
* * EMOJI
* * MESSAGE
* @typedef {string} TargetType
*/
/**
* The target for an audit log entry. It can be one of:
* * A guild * * A guild
* * A user * * A user
* * A role * * A role
@@ -106,13 +148,13 @@ class GuildAuditLogs {
* * An invite * * An invite
* * A webhook * * A webhook
* * An object where the keys represent either the new value or the old value * * An object where the keys represent either the new value or the old value
* @typedef {?Object|Guild|User|Role|Emoji|Invite|Webhook} EntryTarget * @typedef {?Object|Guild|User|Role|Emoji|Invite|Webhook} AuditLogEntryTarget
*/ */
/** /**
* Finds the target type from the entry action. * Finds the target type from the entry action.
* @param {number} target The action target * @param {AuditLogAction} target The action target
* @returns {?string} * @returns {AuditLogTargetType}
*/ */
static targetType(target) { static targetType(target) {
if (target < 10) return Targets.GUILD; if (target < 10) return Targets.GUILD;
@@ -131,13 +173,14 @@ class GuildAuditLogs {
* * CREATE * * CREATE
* * DELETE * * DELETE
* * UPDATE * * UPDATE
* @typedef {string} ActionType * * ALL
* @typedef {string} AuditLogActionType
*/ */
/** /**
* Finds the action type from the entry action. * Finds the action type from the entry action.
* @param {string} action The action target * @param {AuditLogAction} action The action target
* @returns {string} * @returns {AuditLogActionType}
*/ */
static actionType(action) { static actionType(action) {
if ([ if ([
@@ -187,19 +230,19 @@ class GuildAuditLogsEntry {
const targetType = GuildAuditLogs.targetType(data.action_type); const targetType = GuildAuditLogs.targetType(data.action_type);
/** /**
* The target type of this entry * The target type of this entry
* @type {TargetType} * @type {AuditLogTargetType}
*/ */
this.targetType = targetType; this.targetType = targetType;
/** /**
* The action type of this entry * The action type of this entry
* @type {ActionType} * @type {AuditLogActionType}
*/ */
this.actionType = GuildAuditLogs.actionType(data.action_type); this.actionType = GuildAuditLogs.actionType(data.action_type);
/** /**
* Specific action type of this entry * Specific action type of this entry in its string presentation
* @type {string} * @type {AuditLogAction}
*/ */
this.action = Object.keys(Actions).find(k => Actions[k] === data.action_type); this.action = Object.keys(Actions).find(k => Actions[k] === data.action_type);
@@ -271,7 +314,7 @@ class GuildAuditLogsEntry {
if (targetType === Targets.UNKNOWN) { if (targetType === Targets.UNKNOWN) {
/** /**
* The target of this entry * The target of this entry
* @type {EntryTarget} * @type {AuditLogEntryTarget}
*/ */
this.target = this.changes.reduce((o, c) => { this.target = this.changes.reduce((o, c) => {
o[c.key] = c.new || c.old; o[c.key] = c.new || c.old;

View File

@@ -248,6 +248,7 @@ class GuildChannel extends Channel {
* @property {string} [name] The name of the channel * @property {string} [name] The name of the channel
* @property {number} [position] The position of the channel * @property {number} [position] The position of the channel
* @property {string} [topic] The topic of the text channel * @property {string} [topic] The topic of the text channel
* @property {boolean} [nsfw] Whether the channel is NSFW
* @property {number} [bitrate] The bitrate of the voice channel * @property {number} [bitrate] The bitrate of the voice channel
* @property {number} [userLimit] The user limit of the voice channel * @property {number} [userLimit] The user limit of the voice channel
* @property {Snowflake} [parentID] The parent ID of the channel * @property {Snowflake} [parentID] The parent ID of the channel
@@ -290,6 +291,7 @@ class GuildChannel extends Channel {
data: { data: {
name: (data.name || this.name).trim(), name: (data.name || this.name).trim(),
topic: data.topic, topic: data.topic,
nsfw: data.nsfw,
bitrate: data.bitrate || (this.bitrate ? this.bitrate * 1000 : undefined), bitrate: data.bitrate || (this.bitrate ? this.bitrate * 1000 : undefined),
user_limit: data.userLimit != null ? data.userLimit : this.userLimit, // eslint-disable-line eqeqeq user_limit: data.userLimit != null ? data.userLimit : this.userLimit, // eslint-disable-line eqeqeq
parent_id: data.parentID, parent_id: data.parentID,
@@ -491,11 +493,8 @@ class GuildChannel extends Channel {
* When concatenated with a string, this automatically returns the channel's mention instead of the Channel object. * When concatenated with a string, this automatically returns the channel's mention instead of the Channel object.
* @returns {string} * @returns {string}
* @example * @example
* // Outputs: Hello from #general * // Logs: Hello from <#123456789012345678>!
* console.log(`Hello from ${channel}`); * console.log(`Hello from ${channel}!`);
* @example
* // Outputs: Hello from #general
* console.log('Hello from ' + channel);
*/ */
toString() { toString() {
return `<#${this.id}>`; return `<#${this.id}>`;

View File

@@ -125,7 +125,7 @@ class GuildMember extends Base {
* @readonly * @readonly
*/ */
get presence() { get presence() {
return this.frozenPresence || this.guild.presences.get(this.id) || new Presence(); return this.frozenPresence || this.guild.presences.get(this.id) || new Presence(this.client);
} }
/** /**
@@ -294,19 +294,13 @@ class GuildMember extends Base {
/** /**
* Checks if any of the member's roles have a permission. * Checks if any of the member's roles have a permission.
* @param {PermissionResolvable|PermissionResolvable[]} permission Permission(s) to check for * @param {PermissionResolvable|PermissionResolvable[]} permission Permission(s) to check for
* @param {boolean} [explicit=false] Whether to require the role to explicitly have the exact permission * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override
* **(deprecated)** * @param {boolean} [checkOwner=true] Whether to allow being the guild's owner to override
* @param {boolean} [checkAdmin] Whether to allow the administrator permission to override
* (takes priority over `explicit`)
* @param {boolean} [checkOwner] Whether to allow being the guild's owner to override
* (takes priority over `explicit`)
* @returns {boolean} * @returns {boolean}
*/ */
hasPermission(permission, explicit = false, checkAdmin, checkOwner) { hasPermission(permission, checkAdmin = true, checkOwner = true) {
if (typeof checkAdmin === 'undefined') checkAdmin = !explicit;
if (typeof checkOwner === 'undefined') checkOwner = !explicit;
if (checkOwner && this.user.id === this.guild.ownerID) return true; if (checkOwner && this.user.id === this.guild.ownerID) return true;
return this.roles.some(r => r.permissions.has(permission, undefined, checkAdmin)); return this.roles.some(r => r.permissions.has(permission, checkAdmin));
} }
/** /**
@@ -521,7 +515,7 @@ class GuildMember extends Base {
/** /**
* Bans this guild member. * Bans this guild member.
* @param {Object|number|string} [options] Ban options. If a number, the number of days to delete messages for, if a * @param {Object} [options] Ban options. If a number, the number of days to delete messages for, if a
* string, the ban reason. Supplying an object allows you to do both. * string, the ban reason. Supplying an object allows you to do both.
* @param {number} [options.days=0] Number of days of messages to delete * @param {number} [options.days=0] Number of days of messages to delete
* @param {string} [options.reason] Reason for banning * @param {string} [options.reason] Reason for banning
@@ -535,10 +529,10 @@ class GuildMember extends Base {
} }
/** /**
* When concatenated with a string, this automatically concatenates the user's mention instead of the Member object. * When concatenated with a string, this automatically returns the user's mention instead of the GuildMember object.
* @returns {string} * @returns {string}
* @example * @example
* // Logs: Hello from <@123456789>! * // Logs: Hello from <@123456789012345678>!
* console.log(`Hello from ${member}!`); * console.log(`Hello from ${member}!`);
*/ */
toString() { toString() {

View File

@@ -132,12 +132,12 @@ class MessageEmbed {
proxyIconURL: data.footer.proxyIconURL || data.footer.proxy_icon_url, proxyIconURL: data.footer.proxyIconURL || data.footer.proxy_icon_url,
} : null; } : null;
/**
* The files of this embed
* @type {?Object}
* @property {Array<FileOptions|string|MessageAttachment>} files Files to attach
*/
if (data.files) { if (data.files) {
/**
* The files of this embed
* @type {?Object}
* @property {Array<FileOptions|string|MessageAttachment>} files Files to attach
*/
this.files = data.files.map(file => { this.files = data.files.map(file => {
if (file instanceof MessageAttachment) { if (file instanceof MessageAttachment) {
return typeof file.file === 'string' ? file.file : Util.cloneObject(file.file); return typeof file.file === 'string' ? file.file : Util.cloneObject(file.file);
@@ -158,7 +158,7 @@ class MessageEmbed {
/** /**
* The hexadecimal version of the embed color, with a leading hash * The hexadecimal version of the embed color, with a leading hash
* @type {string} * @type {?string}
* @readonly * @readonly
*/ */
get hexColor() { get hexColor() {

View File

@@ -19,7 +19,7 @@ class Presence {
* * **`dnd`** - user is in Do Not Disturb * * **`dnd`** - user is in Do Not Disturb
* @type {string} * @type {string}
*/ */
this.status = data.status || this.status; this.status = data.status || this.status || 'offline';
const activity = data.game || data.activity; const activity = data.game || data.activity;
/** /**
@@ -38,7 +38,7 @@ class Presence {
} }
/** /**
* Whether this presence is equal to another * Whether this presence is equal to another.
* @param {Presence} presence The presence to compare with * @param {Presence} presence The presence to compare with
* @returns {boolean} * @returns {boolean}
*/ */
@@ -160,21 +160,22 @@ class RichPresenceAssets {
/** /**
* ID of the large image asset * ID of the large image asset
* @type {?string} * @type {?Snowflake}
*/ */
this.largeImage = assets.large_image || null; this.largeImage = assets.large_image || null;
/** /**
* ID of the small image asset * ID of the small image asset
* @type {?string} * @type {?Snowflake}
*/ */
this.smallImage = assets.small_image || null; this.smallImage = assets.small_image || null;
} }
/** /**
* Gets the URL of the small image asset * Gets the URL of the small image asset
* @param {string} format Format of the image * @param {Object} [options] Options for the image url
* @param {number} size Size of the image * @param {string} [options.format] Format of the image
* @param {number} [options.size] Size of the image
* @returns {?string} The small image URL * @returns {?string} The small image URL
*/ */
smallImageURL({ format, size } = {}) { smallImageURL({ format, size } = {}) {
@@ -185,8 +186,9 @@ class RichPresenceAssets {
/** /**
* Gets the URL of the large image asset * Gets the URL of the large image asset
* @param {string} format Format of the image * @param {Object} [options] Options for the image url
* @param {number} size Size of the image * @param {string} [options.format] Format of the image
* @param {number} [options.size] Size of the image
* @returns {?string} The large image URL * @returns {?string} The large image URL
*/ */
largeImageURL({ format, size } = {}) { largeImageURL({ format, size } = {}) {

View File

@@ -35,11 +35,12 @@ class ReactionEmoji {
} }
/** /**
* Creates the text required to form a graphical emoji on Discord. * When concatenated with a string, this automatically returns the text required to form a graphical emoji on Discord
* instead of the ReactionEmoji object.
* @returns {string}
* @example * @example
* // Send the emoji used in a reaction to the channel the reaction is part of * // Send the emoji used in a reaction to the channel the reaction is part of
* reaction.message.channel.send(`The emoji used is ${reaction.emoji}`); * reaction.message.channel.send(`The emoji used was: ${reaction.emoji}`);
* @returns {string}
*/ */
toString() { toString() {
return this.id ? `<:${this.name}:${this.id}>` : this.name; return this.id ? `<:${this.name}:${this.id}>` : this.name;

View File

@@ -332,8 +332,11 @@ class Role extends Base {
} }
/** /**
* When concatenated with a string, this automatically concatenates the role mention rather than the Role object. * When concatenated with a string, this automatically returns the role's mention instead of the Role object.
* @returns {string} * @returns {string}
* @example
* // Logs: Role: <@&123456789012345678>
* console.log(`Role: ${role}`);
*/ */
toString() { toString() {
if (this.id === this.guild.id) return '@everyone'; if (this.id === this.guild.id) return '@everyone';

View File

@@ -38,6 +38,16 @@ class TextChannel extends GuildChannel {
if (data.messages) for (const message of data.messages) this.messages.create(message); if (data.messages) for (const message of data.messages) this.messages.create(message);
} }
/**
* Sets whether this channel is flagged as NSFW.
* @param {boolean} nsfw Whether the channel should be considered NSFW
* @param {string} [reason] Reason for changing the channel's NSFW flag
* @returns {Promise<TextChannel>}
*/
setNSFW(nsfw, reason) {
return this.edit({ nsfw }, reason);
}
/** /**
* Fetches all webhooks for the channel. * Fetches all webhooks for the channel.
* @returns {Promise<Collection<Snowflake, Webhook>>} * @returns {Promise<Collection<Snowflake, Webhook>>}

View File

@@ -20,6 +20,13 @@ class User extends Base {
*/ */
this.id = data.id; this.id = data.id;
/**
* Whether or not the user is a bot
* @type {boolean}
* @name User#bot
*/
this.bot = Boolean(data.bot);
this._patch(data); this._patch(data);
} }
@@ -40,18 +47,11 @@ class User extends Base {
/** /**
* The ID of the user's avatar * The ID of the user's avatar
* @type {string} * @type {?string}
* @name User#avatar * @name User#avatar
*/ */
if (typeof data.avatar !== 'undefined') this.avatar = data.avatar; if (typeof data.avatar !== 'undefined') this.avatar = data.avatar;
/**
* Whether or not the user is a bot
* @type {boolean}
* @name User#bot
*/
if (typeof this.bot === 'undefined' && typeof data.bot !== 'undefined') this.bot = Boolean(data.bot);
/** /**
* The ID of the last message sent by the user, if one was sent * The ID of the last message sent by the user, if one was sent
* @type {?Snowflake} * @type {?Snowflake}
@@ -63,8 +63,6 @@ class User extends Base {
* @type {?Message} * @type {?Message}
*/ */
this.lastMessage = null; this.lastMessage = null;
if (data.token) this.client.token = data.token;
} }
/** /**
@@ -95,7 +93,7 @@ class User extends Base {
for (const guild of this.client.guilds.values()) { for (const guild of this.client.guilds.values()) {
if (guild.presences.has(this.id)) return guild.presences.get(this.id); if (guild.presences.has(this.id)) return guild.presences.get(this.id);
} }
return new Presence(); return new Presence(this.client);
} }
/** /**
@@ -250,10 +248,10 @@ class User extends Base {
} }
/** /**
* When concatenated with a string, this automatically concatenates the user's mention instead of the User object. * When concatenated with a string, this automatically returns the user's mention instead of the User object.
* @returns {string} * @returns {string}
* @example * @example
* // logs: Hello from <@123456789>! * // Logs: Hello from <@123456789012345678>!
* console.log(`Hello from ${user}!`); * console.log(`Hello from ${user}!`);
*/ */
toString() { toString() {

View File

@@ -79,7 +79,6 @@ class Webhook {
* (see [here](https://discordapp.com/developers/docs/resources/channel#embed-object) for more details) * (see [here](https://discordapp.com/developers/docs/resources/channel#embed-object) for more details)
* @property {boolean} [disableEveryone=this.client.options.disableEveryone] Whether or not @everyone and @here * @property {boolean} [disableEveryone=this.client.options.disableEveryone] Whether or not @everyone and @here
* should be replaced with plain-text * should be replaced with plain-text
* @property {FileOptions|BufferResolvable} [file] A file to send with the message
* @property {FileOptions[]|string[]} [files] Files to send with the message * @property {FileOptions[]|string[]} [files] Files to send with the message
* @property {string|boolean} [code] Language for optional codeblock formatting to apply * @property {string|boolean} [code] Language for optional codeblock formatting to apply
* @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if * @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if

View File

@@ -11,7 +11,7 @@ const { TypeError } = require('../../errors');
* @property {ChannelResolvable} [channel] Channel to limit search to (only for guild search endpoint) * @property {ChannelResolvable} [channel] Channel to limit search to (only for guild search endpoint)
* @property {UserResolvable} [author] Author to limit search * @property {UserResolvable} [author] Author to limit search
* @property {string} [authorType] One of `user`, `bot`, `webhook`, or add `-` to negate (e.g. `-webhook`) * @property {string} [authorType] One of `user`, `bot`, `webhook`, or add `-` to negate (e.g. `-webhook`)
* @property {string} [sortBy='recent'] `recent` or `relevant` * @property {string} [sortBy='timestamp'] `timestamp` or `relevant`
* @property {string} [sortOrder='descending'] `ascending` or `descending` * @property {string} [sortOrder='descending'] `ascending` or `descending`
* @property {number} [contextSize=2] How many messages to get around the matched message (0 to 2) * @property {number} [contextSize=2] How many messages to get around the matched message (0 to 2)
* @property {number} [limit=25] Maximum number of results to get (1 to 25) * @property {number} [limit=25] Maximum number of results to get (1 to 25)

View File

@@ -114,6 +114,7 @@ exports.Endpoints = {
Asset: name => `${root}/assets/${name}`, Asset: name => `${root}/assets/${name}`,
DefaultAvatar: number => `${root}/embed/avatars/${number}.png`, DefaultAvatar: number => `${root}/embed/avatars/${number}.png`,
Avatar: (userID, hash, format = 'default', size) => { Avatar: (userID, hash, format = 'default', size) => {
if (userID === '1') return hash;
if (format === 'default') format = hash.startsWith('a_') ? 'gif' : 'webp'; if (format === 'default') format = hash.startsWith('a_') ? 'gif' : 'webp';
return makeImageUrl(`${root}/avatars/${userID}/${hash}`, { format, size }); return makeImageUrl(`${root}/avatars/${userID}/${hash}`, { format, size });
}, },