chore: consistency/prettier (#3852)

* chore: consistency/prettier

* chore: rebase

* chore: rebase

* chore: include typings

* fix: include typings file in prettier lint-staged
This commit is contained in:
Crawl
2020-02-29 14:35:57 +01:00
committed by GitHub
parent 6650d50a56
commit c065156a88
127 changed files with 5198 additions and 4513 deletions

View File

@@ -1,12 +1,12 @@
'use strict';
const DataResolver = require('../util/DataResolver');
const MessageEmbed = require('./MessageEmbed');
const MessageAttachment = require('./MessageAttachment');
const { browser } = require('../util/Constants');
const Util = require('../util/Util');
const MessageEmbed = require('./MessageEmbed');
const { RangeError } = require('../errors');
const { browser } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const MessageFlags = require('../util/MessageFlags');
const Util = require('../util/Util');
/**
* Represents a message to be sent to the API.
@@ -78,7 +78,7 @@ class APIMessage {
* Makes the content of this message.
* @returns {?(string|string[])}
*/
makeContent() { // eslint-disable-line complexity
makeContent() {
const GuildMember = require('./GuildMember');
let content;
@@ -88,13 +88,14 @@ class APIMessage {
content = Util.resolveString(this.options.content);
}
const disableMentions = typeof this.options.disableMentions === 'undefined' ?
this.target.client.options.disableMentions :
this.options.disableMentions;
const disableMentions =
typeof this.options.disableMentions === 'undefined'
? this.target.client.options.disableMentions
: this.options.disableMentions;
if (disableMentions === 'all') {
content = Util.removeMentions(content || '');
} else if (disableMentions === 'everyone') {
content = (content || '').replace(/@([^<>@ ]*)/gsmu, (match, target) => {
content = (content || '').replace(/@([^<>@ ]*)/gmsu, (match, target) => {
if (target.match(/^[&!]?\d+$/)) {
return `@${target}`;
} else {
@@ -270,7 +271,8 @@ class APIMessage {
return 'file.jpg';
};
const ownAttachment = typeof fileLike === 'string' ||
const ownAttachment =
typeof fileLike === 'string' ||
fileLike instanceof (browser ? ArrayBuffer : Buffer) ||
typeof fileLike.pipe === 'function';
if (ownAttachment) {

View File

@@ -20,7 +20,9 @@ class Base {
return Object.assign(Object.create(this), this);
}
_patch(data) { return data; }
_patch(data) {
return data;
}
_update(data) {
const clone = this._clone();

View File

@@ -1,8 +1,8 @@
'use strict';
const Snowflake = require('../util/Snowflake');
const Base = require('./Base');
const { ChannelTypes } = require('../util/Constants');
const Snowflake = require('../util/Snowflake');
/**
* Represents any channel on Discord.
@@ -82,7 +82,10 @@ class Channel extends Base {
* .catch(console.error);
*/
delete() {
return this.client.api.channels(this.id).delete().then(() => this);
return this.client.api
.channels(this.id)
.delete()
.then(() => this);
}
/**

View File

@@ -1,9 +1,9 @@
'use strict';
const Snowflake = require('../util/Snowflake');
const { ClientApplicationAssetTypes, Endpoints } = require('../util/Constants');
const Base = require('./Base');
const Team = require('./Team');
const { ClientApplicationAssetTypes, Endpoints } = require('../util/Constants');
const Snowflake = require('../util/Snowflake');
const AssetTypes = Object.keys(ClientApplicationAssetTypes);
@@ -70,11 +70,7 @@ class ClientApplication extends Base {
* The owner of this OAuth application
* @type {?User|Team}
*/
this.owner = data.team ?
new Team(this.client, data.team) :
data.owner ?
this.client.users.add(data.owner) :
null;
this.owner = data.team ? new Team(this.client, data.team) : data.owner ? this.client.users.add(data.owner) : null;
}
/**
@@ -112,9 +108,7 @@ class ClientApplication extends Base {
*/
coverImage({ format, size } = {}) {
if (!this.cover) return null;
return Endpoints
.CDN(this.client.options.http.cdn)
.AppIcon(this.id, this.cover, { format, size });
return Endpoints.CDN(this.client.options.http.cdn).AppIcon(this.id, this.cover, { format, size });
}
/**
@@ -130,12 +124,16 @@ class ClientApplication extends Base {
* @returns {Promise<Array<ClientAsset>>}
*/
fetchAssets() {
return this.client.api.oauth2.applications(this.id).assets.get()
.then(assets => assets.map(a => ({
id: a.id,
name: a.name,
type: AssetTypes[a.type - 1],
})));
return this.client.api.oauth2
.applications(this.id)
.assets.get()
.then(assets =>
assets.map(a => ({
id: a.id,
name: a.name,
type: AssetTypes[a.type - 1],
})),
);
}
/**

View File

@@ -1,9 +1,9 @@
'use strict';
const { Presence } = require('./Presence');
const { TypeError } = require('../errors');
const Collection = require('../util/Collection');
const { ActivityTypes, OPCodes } = require('../util/Constants');
const { TypeError } = require('../errors');
class ClientPresence extends Presence {
/**
@@ -29,7 +29,7 @@ class ClientPresence extends Presence {
return this;
}
async _parse({ status, since, afk, activity }) { // eslint-disable-line complexity
async _parse({ status, since, afk, activity }) {
const applicationID = activity && (activity.application ? activity.application.id || activity.application : null);
let assets = new Collection();
if (activity) {
@@ -47,24 +47,28 @@ class ClientPresence extends Presence {
afk: afk != null ? afk : false, // eslint-disable-line eqeqeq
since: since != null ? since : null, // eslint-disable-line eqeqeq
status: status || this.status,
game: activity ? {
type: activity.type,
name: activity.name,
url: activity.url,
details: activity.details || undefined,
state: activity.state || undefined,
assets: activity.assets ? {
large_text: activity.assets.largeText || undefined,
small_text: activity.assets.smallText || undefined,
large_image: assets.get(activity.assets.largeImage) || activity.assets.largeImage,
small_image: assets.get(activity.assets.smallImage) || activity.assets.smallImage,
} : undefined,
timestamps: activity.timestamps || undefined,
party: activity.party || undefined,
application_id: applicationID || undefined,
secrets: activity.secrets || undefined,
instance: activity.instance || undefined,
} : null,
game: activity
? {
type: activity.type,
name: activity.name,
url: activity.url,
details: activity.details || undefined,
state: activity.state || undefined,
assets: activity.assets
? {
large_text: activity.assets.largeText || undefined,
small_text: activity.assets.smallText || undefined,
large_image: assets.get(activity.assets.largeImage) || activity.assets.largeImage,
small_image: assets.get(activity.assets.smallImage) || activity.assets.smallImage,
}
: undefined,
timestamps: activity.timestamps || undefined,
party: activity.party || undefined,
application_id: applicationID || undefined,
secrets: activity.secrets || undefined,
instance: activity.instance || undefined,
}
: null,
};
if ((status || afk || since) && !activity) {
@@ -72,8 +76,8 @@ class ClientPresence extends Presence {
}
if (packet.game) {
packet.game.type = typeof packet.game.type === 'number' ?
packet.game.type : ActivityTypes.indexOf(packet.game.type);
packet.game.type =
typeof packet.game.type === 'number' ? packet.game.type : ActivityTypes.indexOf(packet.game.type);
}
return packet;

View File

@@ -1,7 +1,7 @@
'use strict';
const Structures = require('../util/Structures');
const DataResolver = require('../util/DataResolver');
const Structures = require('../util/Structures');
/**
* Represents the logged in client's Discord user.
@@ -47,7 +47,9 @@ class ClientUser extends Structures.get('User') {
}
edit(data) {
return this.client.api.users('@me').patch({ data })
return this.client.api
.users('@me')
.patch({ data })
.then(newData => {
this.client.token = newData.token;
const { updated } = this.client.actions.UserUpdate.handle(newData);

View File

@@ -1,8 +1,7 @@
'use strict';
const Snowflake = require('../util/Snowflake');
const Base = require('./Base');
const Snowflake = require('../util/Snowflake');
/**
* Represents an emoji, see {@link GuildEmoji} and {@link ReactionEmoji}.

View File

@@ -1,10 +1,18 @@
'use strict';
const Invite = require('./Invite');
const Integration = require('./Integration');
const Base = require('./Base');
const GuildAuditLogs = require('./GuildAuditLogs');
const Webhook = require('./Webhook');
const Integration = require('./Integration');
const Invite = require('./Invite');
const VoiceRegion = require('./VoiceRegion');
const Webhook = require('./Webhook');
const GuildChannelManager = require('../src/managers/GuildChannelManager');
const GuildEmojiManager = require('../src/managers/GuildEmojiManager');
const GuildMemberManager = require('../src/managers/GuildMemberManager');
const PresenceManager = require('../src/managers/PresenceManager');
const RoleManager = require('../src/managers/RoleManager');
const VoiceStateManager = require('../src/managers/VoiceStateManager');
const Collection = require('../util/Collection');
const {
ChannelTypes,
DefaultMessageNotifications,
@@ -12,19 +20,10 @@ const {
VerificationLevels,
ExplicitContentFilterLevels,
} = require('../util/Constants');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
const DataResolver = require('../util/DataResolver');
const Snowflake = require('../util/Snowflake');
const SystemChannelFlags = require('../util/SystemChannelFlags');
const GuildMemberManager = require('../managers/GuildMemberManager');
const RoleManager = require('../managers/RoleManager');
const GuildEmojiManager = require('../managers/GuildEmojiManager');
const GuildChannelManager = require('../managers/GuildChannelManager');
const PresenceManager = require('../managers/PresenceManager');
const VoiceStateManager = require('../managers/VoiceStateManager');
const Base = require('./Base');
const { Error, TypeError } = require('../errors');
const Util = require('../util/Util');
/**
* Represents a guild (or a server) on Discord.
@@ -110,7 +109,6 @@ class Guild extends Base {
return this.client.ws.shards.get(this.shardID);
}
/* eslint-disable complexity */
/**
* Sets up the guild.
* @param {*} data The raw data of the guild
@@ -279,8 +277,8 @@ class Guild extends Base {
* The value set for the guild's default message notifications
* @type {DefaultMessageNotifications|number}
*/
this.defaultMessageNotifications = DefaultMessageNotifications[data.default_message_notifications] ||
data.default_message_notifications;
this.defaultMessageNotifications =
DefaultMessageNotifications[data.default_message_notifications] || data.default_message_notifications;
/**
* The value set for the guild's system channel flags
@@ -483,9 +481,12 @@ class Guild extends Base {
* @readonly
*/
get owner() {
return this.members.cache.get(this.ownerID) || (this.client.options.partials.includes(PartialTypes.GUILD_MEMBER) ?
this.members.add({ user: { id: this.ownerID } }, true) :
null);
return (
this.members.cache.get(this.ownerID) ||
(this.client.options.partials.includes(PartialTypes.GUILD_MEMBER)
? this.members.add({ user: { id: this.ownerID } }, true)
: null)
);
}
/**
@@ -550,10 +551,12 @@ class Guild extends Base {
* @readonly
*/
get me() {
return this.members.cache.get(this.client.user.id) ||
(this.client.options.partials.includes(PartialTypes.GUILD_MEMBER) ?
this.members.add({ user: { id: this.client.user.id } }, true) :
null);
return (
this.members.cache.get(this.client.user.id) ||
(this.client.options.partials.includes(PartialTypes.GUILD_MEMBER)
? this.members.add({ user: { id: this.client.user.id } }, true)
: null)
);
}
/**
@@ -582,10 +585,13 @@ class Guild extends Base {
* @returns {Promise<Guild>}
*/
fetch() {
return this.client.api.guilds(this.id).get().then(data => {
this._patch(data);
return this;
});
return this.client.api
.guilds(this.id)
.get()
.then(data => {
this._patch(data);
return this;
});
}
/**
@@ -596,14 +602,17 @@ class Guild extends Base {
*/
/**
* Fetches information on a banned user from this guild.
* Fetches information on a banned user from this guild.
* @param {UserResolvable} user The User to fetch the ban info of
* @returns {Promise<BanInfo>}
*/
fetchBan(user) {
const id = this.client.users.resolveID(user);
if (!id) throw new Error('FETCH_BAN_RESOLVE_ID');
return this.client.api.guilds(this.id).bans(id).get()
return this.client.api
.guilds(this.id)
.bans(id)
.get()
.then(ban => ({
reason: ban.reason,
user: this.client.users.add(ban.user),
@@ -615,15 +624,18 @@ class Guild extends Base {
* @returns {Promise<Collection<Snowflake, BanInfo>>}
*/
fetchBans() {
return this.client.api.guilds(this.id).bans.get().then(bans =>
bans.reduce((collection, ban) => {
collection.set(ban.user.id, {
reason: ban.reason,
user: this.client.users.add(ban.user),
});
return collection;
}, new Collection()),
);
return this.client.api
.guilds(this.id)
.bans.get()
.then(bans =>
bans.reduce((collection, ban) => {
collection.set(ban.user.id, {
reason: ban.reason,
user: this.client.users.add(ban.user),
});
return collection;
}, new Collection()),
);
}
/**
@@ -637,11 +649,15 @@ class Guild extends Base {
* .catch(console.error);
*/
fetchIntegrations() {
return this.client.api.guilds(this.id).integrations.get().then(data =>
data.reduce((collection, integration) =>
collection.set(integration.id, new Integration(this.client, integration, this)),
new Collection()),
);
return this.client.api
.guilds(this.id)
.integrations.get()
.then(data =>
data.reduce(
(collection, integration) => collection.set(integration.id, new Integration(this.client, integration, this)),
new Collection(),
),
);
}
/**
@@ -658,7 +674,9 @@ class Guild extends Base {
* @returns {Promise<Guild>}
*/
createIntegration(data, reason) {
return this.client.api.guilds(this.id).integrations.post({ data, reason })
return this.client.api
.guilds(this.id)
.integrations.post({ data, reason })
.then(() => this);
}
@@ -678,7 +696,9 @@ class Guild extends Base {
* .catch(console.error);
*/
fetchInvites() {
return this.client.api.guilds(this.id).invites.get()
return this.client.api
.guilds(this.id)
.invites.get()
.then(inviteItems => {
const invites = new Collection();
for (const inviteItem of inviteItems) {
@@ -705,7 +725,9 @@ class Guild extends Base {
if (!this.features.includes('VANITY_URL')) {
return Promise.reject(new Error('VANITY_URL'));
}
return this.client.api.guilds(this.id, 'vanity-url').get()
return this.client.api
.guilds(this.id, 'vanity-url')
.get()
.then(res => res.code);
}
@@ -719,11 +741,14 @@ class Guild extends Base {
* .catch(console.error);
*/
fetchWebhooks() {
return this.client.api.guilds(this.id).webhooks.get().then(data => {
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
});
return this.client.api
.guilds(this.id)
.webhooks.get()
.then(data => {
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
});
}
/**
@@ -731,11 +756,14 @@ class Guild extends Base {
* @returns {Promise<Collection<string, VoiceRegion>>}
*/
fetchVoiceRegions() {
return this.client.api.guilds(this.id).regions.get().then(res => {
const regions = new Collection();
for (const region of res) regions.set(region.id, new VoiceRegion(region));
return regions;
});
return this.client.api
.guilds(this.id)
.regions.get()
.then(res => {
const regions = new Collection();
for (const region of res) regions.set(region.id, new VoiceRegion(region));
return regions;
});
}
/**
@@ -755,10 +783,13 @@ class Guild extends Base {
* .catch(console.error);
*/
fetchEmbed() {
return this.client.api.guilds(this.id).embed.get().then(data => ({
enabled: data.enabled,
channel: data.channel_id ? this.channels.cache.get(data.channel_id) : null,
}));
return this.client.api
.guilds(this.id)
.embed.get()
.then(data => ({
enabled: data.enabled,
channel: data.channel_id ? this.channels.cache.get(data.channel_id) : null,
}));
}
/**
@@ -779,12 +810,16 @@ class Guild extends Base {
if (options.before && options.before instanceof GuildAuditLogs.Entry) options.before = options.before.id;
if (typeof options.type === 'string') options.type = GuildAuditLogs.Actions[options.type];
return this.client.api.guilds(this.id)['audit-logs'].get({ query: {
before: options.before,
limit: options.limit,
user_id: this.client.users.resolveID(options.user),
action_type: options.type,
} })
return this.client.api
.guilds(this.id)
['audit-logs'].get({
query: {
before: options.before,
limit: options.limit,
user_id: this.client.users.resolveID(options.user),
action_type: options.type,
},
})
.then(data => GuildAuditLogs.build(this, data));
}
@@ -811,14 +846,18 @@ class Guild extends Base {
for (let role of options.roles instanceof Collection ? options.roles.values() : options.roles) {
role = this.roles.resolve(role);
if (!role) {
return Promise.reject(new TypeError('INVALID_TYPE', 'options.roles',
'Array or Collection of Roles or Snowflakes', true));
return Promise.reject(
new TypeError('INVALID_TYPE', 'options.roles', 'Array or Collection of Roles or Snowflakes', true),
);
}
roles.push(role.id);
}
options.roles = roles;
}
return this.client.api.guilds(this.id).members(user).put({ data: options })
return this.client.api
.guilds(this.id)
.members(user)
.put({ data: options })
.then(data => this.members.add(data));
}
@@ -859,9 +898,10 @@ class Guild extends Base {
if (data.name) _data.name = data.name;
if (data.region) _data.region = data.region;
if (typeof data.verificationLevel !== 'undefined') {
_data.verification_level = typeof data.verificationLevel === 'number' ?
Number(data.verificationLevel) :
ExplicitContentFilterLevels.indexOf(data.verificationLevel);
_data.verification_level =
typeof data.verificationLevel === 'number'
? Number(data.verificationLevel)
: ExplicitContentFilterLevels.indexOf(data.verificationLevel);
}
if (typeof data.afkChannel !== 'undefined') {
_data.afk_channel_id = this.client.channels.resolveID(data.afkChannel);
@@ -875,19 +915,23 @@ class Guild extends Base {
if (data.splash) _data.splash = data.splash;
if (data.banner) _data.banner = data.banner;
if (typeof data.explicitContentFilter !== 'undefined') {
_data.explicit_content_filter = typeof data.explicitContentFilter === 'number' ?
data.explicitContentFilter :
ExplicitContentFilterLevels.indexOf(data.explicitContentFilter);
_data.explicit_content_filter =
typeof data.explicitContentFilter === 'number'
? data.explicitContentFilter
: ExplicitContentFilterLevels.indexOf(data.explicitContentFilter);
}
if (typeof data.defaultMessageNotifications !== 'undefined') {
_data.default_message_notifications = typeof data.defaultMessageNotifications === 'string' ?
DefaultMessageNotifications.indexOf(data.defaultMessageNotifications) :
data.defaultMessageNotifications;
_data.default_message_notifications =
typeof data.defaultMessageNotifications === 'string'
? DefaultMessageNotifications.indexOf(data.defaultMessageNotifications)
: data.defaultMessageNotifications;
}
if (typeof data.systemChannelFlags !== 'undefined') {
_data.system_channel_flags = SystemChannelFlags.resolve(data.systemChannelFlags);
}
return this.client.api.guilds(this.id).patch({ data: _data, reason })
return this.client.api
.guilds(this.id)
.patch({ data: _data, reason })
.then(newData => this.client.actions.GuildUpdate.handle(newData).updated);
}
@@ -1094,12 +1138,16 @@ class Guild extends Base {
position: r.position,
}));
return this.client.api.guilds(this.id).channels.patch({ data: updatedChannels }).then(() =>
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.id,
channels: updatedChannels,
}).guild,
);
return this.client.api
.guilds(this.id)
.channels.patch({ data: updatedChannels })
.then(
() =>
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.id,
channels: updatedChannels,
}).guild,
);
}
/**
@@ -1126,14 +1174,18 @@ class Guild extends Base {
}));
// Call the API to update role positions
return this.client.api.guilds(this.id).roles.patch({
data: rolePositions,
}).then(() =>
this.client.actions.GuildRolePositionUpdate.handle({
guild_id: this.id,
roles: rolePositions,
}).guild,
);
return this.client.api
.guilds(this.id)
.roles.patch({
data: rolePositions,
})
.then(
() =>
this.client.actions.GuildRolePositionUpdate.handle({
guild_id: this.id,
roles: rolePositions,
}).guild,
);
}
/**
@@ -1143,13 +1195,16 @@ class Guild extends Base {
* @returns {Promise<Guild>}
*/
setEmbed(embed, reason) {
return this.client.api.guilds(this.id).embed.patch({
data: {
enabled: embed.enabled,
channel_id: this.channels.resolveID(embed.channel),
},
reason,
}).then(() => this);
return this.client.api
.guilds(this.id)
.embed.patch({
data: {
enabled: embed.enabled,
channel_id: this.channels.resolveID(embed.channel),
},
reason,
})
.then(() => this);
}
/**
@@ -1163,7 +1218,10 @@ class Guild extends Base {
*/
leave() {
if (this.ownerID === this.client.user.id) return Promise.reject(new Error('GUILD_OWNED'));
return this.client.api.users('@me').guilds(this.id).delete()
return this.client.api
.users('@me')
.guilds(this.id)
.delete()
.then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild);
}
@@ -1177,7 +1235,9 @@ class Guild extends Base {
* .catch(console.error);
*/
delete() {
return this.client.api.guilds(this.id).delete()
return this.client.api
.guilds(this.id)
.delete()
.then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild);
}
@@ -1203,10 +1263,9 @@ class Guild extends Base {
this.ownerID === guild.ownerID &&
this.verificationLevel === guild.verificationLevel &&
this.embedEnabled === guild.embedEnabled &&
(this.features === guild.features || (
this.features.length === guild.features.length &&
this.features.every((feat, i) => feat === guild.features[i]))
);
(this.features === guild.features ||
(this.features.length === guild.features.length &&
this.features.every((feat, i) => feat === guild.features[i])));
if (equal) {
if (this.embedChannel) {
@@ -1261,9 +1320,9 @@ class Guild extends Base {
*/
_sortedChannels(channel) {
const category = channel.type === ChannelTypes.CATEGORY;
return Util.discordSort(this.channels.cache.filter(c =>
c.type === channel.type && (category || c.parent === channel.parent),
));
return Util.discordSort(
this.channels.cache.filter(c => c.type === channel.type && (category || c.parent === channel.parent)),
);
}
}

View File

@@ -1,11 +1,11 @@
'use strict';
const Collection = require('../util/Collection');
const Integration = require('./Integration');
const Snowflake = require('../util/Snowflake');
const Webhook = require('./Webhook');
const Util = require('../util/Util');
const Collection = require('../util/Collection');
const { PartialTypes } = require('../util/Constants');
const Snowflake = require('../util/Snowflake');
const Util = require('../util/Util');
/**
* The target type of an entry, e.g. `GUILD`. Here are the available types:
@@ -125,7 +125,6 @@ const Actions = {
INTEGRATION_DELETE: 82,
};
/**
* Audit logs entries are held in this class.
*/
@@ -223,49 +222,61 @@ class GuildAuditLogs {
* @returns {AuditLogActionType}
*/
static actionType(action) {
if ([
Actions.CHANNEL_CREATE,
Actions.CHANNEL_OVERWRITE_CREATE,
Actions.MEMBER_BAN_REMOVE,
Actions.BOT_ADD,
Actions.ROLE_CREATE,
Actions.INVITE_CREATE,
Actions.WEBHOOK_CREATE,
Actions.EMOJI_CREATE,
Actions.MESSAGE_PIN,
Actions.INTEGRATION_CREATE,
].includes(action)) return 'CREATE';
if (
[
Actions.CHANNEL_CREATE,
Actions.CHANNEL_OVERWRITE_CREATE,
Actions.MEMBER_BAN_REMOVE,
Actions.BOT_ADD,
Actions.ROLE_CREATE,
Actions.INVITE_CREATE,
Actions.WEBHOOK_CREATE,
Actions.EMOJI_CREATE,
Actions.MESSAGE_PIN,
Actions.INTEGRATION_CREATE,
].includes(action)
) {
return 'CREATE';
}
if ([
Actions.CHANNEL_DELETE,
Actions.CHANNEL_OVERWRITE_DELETE,
Actions.MEMBER_KICK,
Actions.MEMBER_PRUNE,
Actions.MEMBER_BAN_ADD,
Actions.MEMBER_DISCONNECT,
Actions.ROLE_DELETE,
Actions.INVITE_DELETE,
Actions.WEBHOOK_DELETE,
Actions.EMOJI_DELETE,
Actions.MESSAGE_DELETE,
Actions.MESSAGE_BULK_DELETE,
Actions.MESSAGE_UNPIN,
Actions.INTEGRATION_DELETE,
].includes(action)) return 'DELETE';
if (
[
Actions.CHANNEL_DELETE,
Actions.CHANNEL_OVERWRITE_DELETE,
Actions.MEMBER_KICK,
Actions.MEMBER_PRUNE,
Actions.MEMBER_BAN_ADD,
Actions.MEMBER_DISCONNECT,
Actions.ROLE_DELETE,
Actions.INVITE_DELETE,
Actions.WEBHOOK_DELETE,
Actions.EMOJI_DELETE,
Actions.MESSAGE_DELETE,
Actions.MESSAGE_BULK_DELETE,
Actions.MESSAGE_UNPIN,
Actions.INTEGRATION_DELETE,
].includes(action)
) {
return 'DELETE';
}
if ([
Actions.GUILD_UPDATE,
Actions.CHANNEL_UPDATE,
Actions.CHANNEL_OVERWRITE_UPDATE,
Actions.MEMBER_UPDATE,
Actions.MEMBER_ROLE_UPDATE,
Actions.MEMBER_MOVE,
Actions.ROLE_UPDATE,
Actions.INVITE_UPDATE,
Actions.WEBHOOK_UPDATE,
Actions.EMOJI_UPDATE,
Actions.INTEGRATION_UPDATE,
].includes(action)) return 'UPDATE';
if (
[
Actions.GUILD_UPDATE,
Actions.CHANNEL_UPDATE,
Actions.CHANNEL_OVERWRITE_UPDATE,
Actions.MEMBER_UPDATE,
Actions.MEMBER_ROLE_UPDATE,
Actions.MEMBER_MOVE,
Actions.ROLE_UPDATE,
Actions.INVITE_UPDATE,
Actions.WEBHOOK_UPDATE,
Actions.EMOJI_UPDATE,
Actions.INTEGRATION_UPDATE,
].includes(action)
) {
return 'UPDATE';
}
return 'ALL';
}
@@ -279,7 +290,7 @@ class GuildAuditLogs {
* Audit logs entry.
*/
class GuildAuditLogsEntry {
constructor(logs, guild, data) { // eslint-disable-line complexity
constructor(logs, guild, data) {
const targetType = GuildAuditLogs.targetType(data.action_type);
/**
* The target type of this entry
@@ -309,9 +320,9 @@ class GuildAuditLogsEntry {
* The user that executed this entry
* @type {User}
*/
this.executor = guild.client.options.partials.includes(PartialTypes.USER) ?
guild.client.users.add({ id: data.user_id }) :
guild.client.users.cache.get(data.user_id);
this.executor = guild.client.options.partials.includes(PartialTypes.USER)
? guild.client.users.add({ id: data.user_id })
: guild.client.users.cache.get(data.user_id);
/**
* An entry in the audit log representing a specific change.
@@ -374,13 +385,15 @@ class GuildAuditLogsEntry {
case Actions.CHANNEL_OVERWRITE_DELETE:
switch (data.options.type) {
case 'member':
this.extra = guild.members.cache.get(data.options.id) ||
{ id: data.options.id, type: 'member' };
this.extra = guild.members.cache.get(data.options.id) || { id: data.options.id, type: 'member' };
break;
case 'role':
this.extra = guild.roles.cache.get(data.options.id) ||
{ id: data.options.id, name: data.options.role_name, type: 'role' };
this.extra = guild.roles.cache.get(data.options.id) || {
id: data.options.id,
name: data.options.role_name,
type: 'role',
};
break;
default:
@@ -405,21 +418,27 @@ class GuildAuditLogsEntry {
this.target.id = data.target_id;
// MEMBER_DISCONNECT and similar types do not provide a target_id.
} else if (targetType === Targets.USER && data.target_id) {
this.target = guild.client.options.partials.includes(PartialTypes.USER) ?
guild.client.users.add({ id: data.target_id }) :
guild.client.users.cache.get(data.target_id);
this.target = guild.client.options.partials.includes(PartialTypes.USER)
? guild.client.users.add({ id: data.target_id })
: guild.client.users.cache.get(data.target_id);
} else if (targetType === Targets.GUILD) {
this.target = guild.client.guilds.cache.get(data.target_id);
} else if (targetType === Targets.WEBHOOK) {
this.target = logs.webhooks.get(data.target_id) ||
new Webhook(guild.client,
this.changes.reduce((o, c) => {
o[c.key] = c.new || c.old;
return o;
}, {
id: data.target_id,
guild_id: guild.id,
}));
this.target =
logs.webhooks.get(data.target_id) ||
new Webhook(
guild.client,
this.changes.reduce(
(o, c) => {
o[c.key] = c.new || c.old;
return o;
},
{
id: data.target_id,
guild_id: guild.id,
},
),
);
} else if (targetType === Targets.INVITE) {
this.target = guild.members.fetch(guild.client.user.id).then(me => {
if (me.permissions.has('MANAGE_GUILD')) {
@@ -437,15 +456,24 @@ class GuildAuditLogsEntry {
});
} else if (targetType === Targets.MESSAGE) {
// Discord sends a channel id for the MESSAGE_BULK_DELETE action type.
this.target = data.action_type === Actions.MESSAGE_BULK_DELETE ?
guild.channels.cache.get(data.target_id) || { id: data.target_id } :
guild.client.users.cache.get(data.target_id);
this.target =
data.action_type === Actions.MESSAGE_BULK_DELETE
? guild.channels.cache.get(data.target_id) || { id: data.target_id }
: guild.client.users.cache.get(data.target_id);
} else if (targetType === Targets.INTEGRATION) {
this.target = logs.integrations.get(data.target_id) ||
new Integration(guild.client, this.changes.reduce((o, c) => {
o[c.key] = c.new || c.old;
return o;
}, { id: data.target_id }), guild);
this.target =
logs.integrations.get(data.target_id) ||
new Integration(
guild.client,
this.changes.reduce(
(o, c) => {
o[c.key] = c.new || c.old;
return o;
},
{ id: data.target_id },
),
guild,
);
} else if (data.target_id) {
this.target = guild[`${targetType.toLowerCase()}s`].cache.get(data.target_id) || { id: data.target_id };
}

View File

@@ -1,13 +1,13 @@
'use strict';
const Channel = require('./Channel');
const Role = require('./Role');
const Invite = require('./Invite');
const PermissionOverwrites = require('./PermissionOverwrites');
const Util = require('../util/Util');
const Permissions = require('../util/Permissions');
const Collection = require('../util/Collection');
const Role = require('./Role');
const { Error, TypeError } = require('../errors');
const Collection = require('../util/Collection');
const Permissions = require('../util/Permissions');
const Util = require('../util/Util');
/**
* Represents a guild channel from any of the following:
@@ -85,9 +85,11 @@ class GuildChannel extends Channel {
if (this.permissionOverwrites.size !== this.parent.permissionOverwrites.size) return false;
return this.permissionOverwrites.every((value, key) => {
const testVal = this.parent.permissionOverwrites.get(key);
return testVal !== undefined &&
return (
testVal !== undefined &&
testVal.deny.bitfield === value.deny.bitfield &&
testVal.allow.bitfield === value.allow.bitfield;
testVal.allow.bitfield === value.allow.bitfield
);
});
}
@@ -202,12 +204,9 @@ class GuildChannel extends Channel {
*/
overwritePermissions(overwrites, reason) {
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
return Promise.reject(new TypeError(
'INVALID_TYPE',
'overwrites',
'Array or Collection of Permission Overwrites',
true,
));
return Promise.reject(
new TypeError('INVALID_TYPE', 'overwrites', 'Array or Collection of Permission Overwrites', true),
);
}
return this.edit({ permissionOverwrites: overwrites, reason }).then(() => this);
}
@@ -256,8 +255,12 @@ class GuildChannel extends Channel {
const type = userOrRole instanceof Role ? 'role' : 'member';
const { allow, deny } = PermissionOverwrites.resolveOverwriteOptions(options);
return this.client.api.channels(this.id).permissions[userOrRole.id]
.put({ data: { id: userOrRole.id, type, allow: allow.bitfield, deny: deny.bitfield }, reason })
return this.client.api
.channels(this.id)
.permissions[userOrRole.id].put({
data: { id: userOrRole.id, type, allow: allow.bitfield, deny: deny.bitfield },
reason,
})
.then(() => this);
}
@@ -316,18 +319,23 @@ class GuildChannel extends Channel {
*/
async edit(data, reason) {
if (typeof data.position !== 'undefined') {
await Util.setPosition(this, data.position, false,
this.guild._sortedChannels(this), this.client.api.guilds(this.guild.id).channels, reason)
.then(updatedChannels => {
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
await Util.setPosition(
this,
data.position,
false,
this.guild._sortedChannels(this),
this.client.api.guilds(this.guild.id).channels,
reason,
).then(updatedChannels => {
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
});
}
const permission_overwrites = data.permissionOverwrites &&
data.permissionOverwrites.map(o => PermissionOverwrites.resolve(o, this.guild));
const permission_overwrites =
data.permissionOverwrites && data.permissionOverwrites.map(o => PermissionOverwrites.resolve(o, this.guild));
const newData = await this.client.api.channels(this.id).patch({
data: {
@@ -378,11 +386,14 @@ class GuildChannel extends Channel {
* .catch(console.error);
*/
setParent(channel, { lockPermissions = true, reason } = {}) {
return this.edit({
// eslint-disable-next-line no-prototype-builtins
parentID: channel !== null ? channel.hasOwnProperty('id') ? channel.id : channel : null,
lockPermissions,
}, reason);
return this.edit(
{
// eslint-disable-next-line no-prototype-builtins
parentID: channel !== null ? (channel.hasOwnProperty('id') ? channel.id : channel) : null,
lockPermissions,
},
reason,
);
}
/**
@@ -414,15 +425,20 @@ class GuildChannel extends Channel {
* .catch(console.error);
*/
setPosition(position, { relative, reason } = {}) {
return Util.setPosition(this, position, relative,
this.guild._sortedChannels(this), this.client.api.guilds(this.guild.id).channels, reason)
.then(updatedChannels => {
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
return this;
return Util.setPosition(
this,
position,
relative,
this.guild._sortedChannels(this),
this.client.api.guilds(this.guild.id).channels,
reason,
).then(updatedChannels => {
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
return this;
});
}
/**
@@ -442,9 +458,17 @@ class GuildChannel extends Channel {
* .catch(console.error);
*/
createInvite({ temporary = false, maxAge = 86400, maxUses = 0, unique, reason } = {}) {
return this.client.api.channels(this.id).invites.post({ data: {
temporary, max_age: maxAge, max_uses: maxUses, unique,
}, reason })
return this.client.api
.channels(this.id)
.invites.post({
data: {
temporary,
max_age: maxAge,
max_uses: maxUses,
unique,
},
reason,
})
.then(invite => new Invite(this.client, invite));
}
@@ -481,18 +505,21 @@ class GuildChannel extends Channel {
* @returns {Promise<GuildChannel>}
*/
clone(options = {}) {
Util.mergeDefault({
name: this.name,
permissionOverwrites: this.permissionOverwrites,
topic: this.topic,
type: this.type,
nsfw: this.nsfw,
parent: this.parent,
bitrate: this.bitrate,
userLimit: this.userLimit,
rateLimitPerUser: this.rateLimitPerUser,
reason: null,
}, options);
Util.mergeDefault(
{
name: this.name,
permissionOverwrites: this.permissionOverwrites,
topic: this.topic,
type: this.type,
nsfw: this.nsfw,
parent: this.parent,
bitrate: this.bitrate,
userLimit: this.userLimit,
rateLimitPerUser: this.rateLimitPerUser,
reason: null,
},
options,
);
return this.guild.channels.create(options.name, options);
}
/* eslint-enable max-len */
@@ -504,7 +531,8 @@ class GuildChannel extends Channel {
* @returns {boolean}
*/
equals(channel) {
let equal = channel &&
let equal =
channel &&
this.id === channel.id &&
this.type === channel.type &&
this.topic === channel.topic &&
@@ -565,7 +593,10 @@ class GuildChannel extends Channel {
* .catch(console.error);
*/
delete(reason) {
return this.client.api.channels(this.id).delete({ reason }).then(() => this);
return this.client.api
.channels(this.id)
.delete({ reason })
.then(() => this);
}
}

View File

@@ -1,9 +1,9 @@
'use strict';
const Emoji = require('./Emoji');
const { Error } = require('../errors');
const GuildEmojiRoleManager = require('../managers/GuildEmojiRoleManager');
const Permissions = require('../util/Permissions');
const { Error } = require('../errors');
const Emoji = require('./Emoji');
/**
* Represents a custom emoji.
@@ -74,8 +74,7 @@ class GuildEmoji extends Emoji {
*/
get deletable() {
if (!this.guild.me) throw new Error('GUILD_UNCACHED_ME');
return !this.managed &&
this.guild.me.hasPermission(Permissions.FLAGS.MANAGE_EMOJIS);
return !this.managed && this.guild.me.hasPermission(Permissions.FLAGS.MANAGE_EMOJIS);
}
/**
@@ -100,7 +99,10 @@ class GuildEmoji extends Emoji {
return Promise.reject(new Error('MISSING_MANAGE_EMOJIS_PERMISSION', this.guild));
}
}
return this.client.api.guilds(this.guild.id).emojis(this.id).get()
return this.client.api
.guilds(this.guild.id)
.emojis(this.id)
.get()
.then(emoji => this.client.users.add(emoji.user));
}
@@ -124,11 +126,16 @@ class GuildEmoji extends Emoji {
*/
edit(data, reason) {
const roles = data.roles ? data.roles.map(r => r.id || r) : undefined;
return this.client.api.guilds(this.guild.id).emojis(this.id)
.patch({ data: {
name: data.name,
roles,
}, reason })
return this.client.api
.guilds(this.guild.id)
.emojis(this.id)
.patch({
data: {
name: data.name,
roles,
},
reason,
})
.then(newData => {
const clone = this._clone();
clone._patch(newData);
@@ -152,7 +159,10 @@ class GuildEmoji extends Emoji {
* @returns {Promise<GuildEmoji>}
*/
delete(reason) {
return this.client.api.guilds(this.guild.id).emojis(this.id).delete({ reason })
return this.client.api
.guilds(this.guild.id)
.emojis(this.id)
.delete({ reason })
.then(() => this);
}

View File

@@ -1,13 +1,13 @@
'use strict';
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const Role = require('./Role');
const Permissions = require('../util/Permissions');
const GuildMemberRoleManager = require('../managers/GuildMemberRoleManager');
const Base = require('./Base');
const VoiceState = require('./VoiceState');
const { Presence } = require('./Presence');
const Role = require('./Role');
const VoiceState = require('./VoiceState');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Error } = require('../errors');
const GuildMemberRoleManager = require('../managers/GuildMemberRoleManager');
const Permissions = require('../util/Permissions');
/**
* Represents a member of a guild on Discord.
@@ -152,12 +152,15 @@ class GuildMember extends Base {
* @readonly
*/
get presence() {
return this.guild.presences.cache.get(this.id) || new Presence(this.client, {
user: {
id: this.id,
},
guild: this.guild,
});
return (
this.guild.presences.cache.get(this.id) ||
new Presence(this.client, {
user: {
id: this.id,
},
guild: this.guild,
})
);
}
/**
@@ -293,7 +296,7 @@ class GuildMember extends Base {
data.channel_id = null;
data.channel = undefined;
}
if (data.roles) data.roles = data.roles.map(role => role instanceof Role ? role.id : role);
if (data.roles) data.roles = data.roles.map(role => (role instanceof Role ? role.id : role));
let endpoint = this.client.api.guilds(this.guild.id);
if (this.user.id === this.client.user.id) {
const keys = Object.keys(data);
@@ -342,7 +345,10 @@ class GuildMember extends Base {
* @returns {Promise<GuildMember>}
*/
kick(reason) {
return this.client.api.guilds(this.guild.id).members(this.user.id).delete({ reason })
return this.client.api
.guilds(this.guild.id)
.members(this.user.id)
.delete({ reason })
.then(() => this);
}

View File

@@ -98,7 +98,10 @@ class Integration extends Base {
*/
sync() {
this.syncing = true;
return this.client.api.guilds(this.guild.id).integrations(this.id).post()
return this.client.api
.guilds(this.guild.id)
.integrations(this.id)
.post()
.then(() => {
this.syncing = false;
this.syncedAt = Date.now();
@@ -129,7 +132,10 @@ class Integration extends Base {
data.expireGracePeriod = null;
}
// The option enable_emoticons is only available for Twitch at this moment
return this.client.api.guilds(this.guild.id).integrations(this.id).patch({ data, reason })
return this.client.api
.guilds(this.guild.id)
.integrations(this.id)
.patch({ data, reason })
.then(() => {
this._patch(data);
return this;
@@ -142,7 +148,10 @@ class Integration extends Base {
* @param {string} [reason] Reason for deleting this integration
*/
delete(reason) {
return this.client.api.guilds(this.guild.id).integrations(this.id).delete({ reason })
return this.client.api
.guilds(this.guild.id)
.integrations(this.id)
.delete({ reason })
.then(() => this);
}

View File

@@ -1,8 +1,8 @@
'use strict';
const Base = require('./Base');
const { Endpoints } = require('../util/Constants');
const Permissions = require('../util/Permissions');
const Base = require('./Base');
/**
* Represents an invitation to a guild channel.
@@ -119,8 +119,10 @@ class Invite extends Base {
const guild = this.guild;
if (!guild || !this.client.guilds.cache.has(guild.id)) return false;
if (!guild.me) throw new Error('GUILD_UNCACHED_ME');
return this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_CHANNELS, false) ||
guild.me.permissions.has(Permissions.FLAGS.MANAGE_GUILD);
return (
this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_CHANNELS, false) ||
guild.me.permissions.has(Permissions.FLAGS.MANAGE_GUILD)
);
}
/**
@@ -129,7 +131,7 @@ class Invite extends Base {
* @readonly
*/
get expiresTimestamp() {
return this.createdTimestamp && this.maxAge ? this.createdTimestamp + (this.maxAge * 1000) : null;
return this.createdTimestamp && this.maxAge ? this.createdTimestamp + this.maxAge * 1000 : null;
}
/**

View File

@@ -1,19 +1,19 @@
'use strict';
const Mentions = require('./MessageMentions');
const APIMessage = require('./APIMessage');
const Base = require('./Base');
const ClientApplication = require('./ClientApplication');
const MessageAttachment = require('./MessageAttachment');
const Embed = require('./MessageEmbed');
const Mentions = require('./MessageMentions');
const ReactionCollector = require('./ReactionCollector');
const ClientApplication = require('./ClientApplication');
const Util = require('../util/Util');
const Collection = require('../util/Collection');
const ReactionManager = require('../managers/ReactionManager');
const { MessageTypes } = require('../util/Constants');
const Permissions = require('../util/Permissions');
const Base = require('./Base');
const { Error, TypeError } = require('../errors');
const APIMessage = require('./APIMessage');
const ReactionManager = require('../managers/ReactionManager');
const Collection = require('../util/Collection');
const { MessageTypes } = require('../util/Constants');
const MessageFlags = require('../util/MessageFlags');
const Permissions = require('../util/Permissions');
const Util = require('../util/Util');
/**
* Represents a message on Discord.
@@ -43,7 +43,7 @@ class Message extends Base {
if (data) this._patch(data);
}
_patch(data) { // eslint-disable-line complexity
_patch(data) {
/**
* The ID of the message
* @type {Snowflake}
@@ -107,9 +107,7 @@ class Message extends Base {
this.attachments = new Collection();
if (data.attachments) {
for (const attachment of data.attachments) {
this.attachments.set(attachment.id, new MessageAttachment(
attachment.url, attachment.filename, attachment,
));
this.attachments.set(attachment.id, new MessageAttachment(attachment.url, attachment.filename, attachment));
}
}
@@ -158,10 +156,12 @@ class Message extends Base {
* Group activity
* @type {?MessageActivity}
*/
this.activity = data.activity ? {
partyID: data.activity.party_id,
type: data.activity.type,
} : null;
this.activity = data.activity
? {
partyID: data.activity.party_id,
type: data.activity.type,
}
: null;
/**
* The previous versions of the message, sorted with the most recent first
@@ -194,11 +194,13 @@ class Message extends Base {
* Message reference data
* @type {?MessageReference}
*/
this.reference = data.message_reference ? {
channelID: data.message_reference.channel_id,
guildID: data.message_reference.guild_id,
messageID: data.message_reference.message_id,
} : null;
this.reference = data.message_reference
? {
channelID: data.message_reference.channel_id,
guildID: data.message_reference.guild_id,
messageID: data.message_reference.message_id,
}
: null;
}
/**
@@ -229,9 +231,7 @@ class Message extends Base {
if ('attachments' in data) {
this.attachments = new Collection();
for (const attachment of data.attachments) {
this.attachments.set(attachment.id, new MessageAttachment(
attachment.url, attachment.filename, attachment,
));
this.attachments.set(attachment.id, new MessageAttachment(attachment.url, attachment.filename, attachment));
}
} else {
this.attachments = new Collection(this.attachments);
@@ -377,9 +377,11 @@ class Message extends Base {
* @readonly
*/
get deletable() {
return !this.deleted && (this.author.id === this.client.user.id || (this.guild &&
this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES, false)
));
return (
!this.deleted &&
(this.author.id === this.client.user.id ||
(this.guild && this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES, false)))
);
}
/**
@@ -388,8 +390,10 @@ class Message extends Base {
* @readonly
*/
get pinnable() {
return this.type === 'DEFAULT' && (!this.guild ||
this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES, false));
return (
this.type === 'DEFAULT' &&
(!this.guild || this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES, false))
);
}
/**
@@ -412,16 +416,13 @@ class Message extends Base {
* .catch(console.error);
*/
edit(content, options) {
const { data } = content instanceof APIMessage ?
content.resolveData() :
APIMessage.create(this, content, options).resolveData();
return this.client.api.channels[this.channel.id].messages[this.id]
.patch({ data })
.then(d => {
const clone = this._clone();
clone._patch(d);
return clone;
});
const { data } =
content instanceof APIMessage ? content.resolveData() : APIMessage.create(this, content, options).resolveData();
return this.client.api.channels[this.channel.id].messages[this.id].patch({ data }).then(d => {
const clone = this._clone();
clone._patch(d);
return clone;
});
}
/**
@@ -429,7 +430,10 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
pin() {
return this.client.api.channels(this.channel.id).pins(this.id).put()
return this.client.api
.channels(this.channel.id)
.pins(this.id)
.put()
.then(() => this);
}
@@ -438,7 +442,10 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
unpin() {
return this.client.api.channels(this.channel.id).pins(this.id).delete()
return this.client.api
.channels(this.channel.id)
.pins(this.id)
.delete()
.then(() => this);
}
@@ -461,14 +468,20 @@ class Message extends Base {
emoji = this.client.emojis.resolveIdentifier(emoji);
if (!emoji) throw new TypeError('EMOJI_TYPE');
return this.client.api.channels(this.channel.id).messages(this.id).reactions(emoji, '@me')
return this.client.api
.channels(this.channel.id)
.messages(this.id)
.reactions(emoji, '@me')
.put()
.then(() => this.client.actions.MessageReactionAdd.handle({
user: this.client.user,
channel: this.channel,
message: this,
emoji: Util.parseEmoji(emoji),
}).reaction);
.then(
() =>
this.client.actions.MessageReactionAdd.handle({
user: this.client.user,
channel: this.channel,
message: this,
emoji: Util.parseEmoji(emoji),
}).reaction,
);
}
/**
@@ -509,9 +522,10 @@ class Message extends Base {
* .catch(console.error);
*/
reply(content, options) {
return this.channel.send(content instanceof APIMessage ?
content :
APIMessage.transformOptions(content, options, { reply: this.member || this.author }),
return this.channel.send(
content instanceof APIMessage
? content
: APIMessage.transformOptions(content, options, { reply: this.member || this.author }),
);
}
@@ -562,16 +576,18 @@ class Message extends Base {
const embedUpdate = !message.author && !message.attachments;
if (embedUpdate) return this.id === message.id && this.embeds.length === message.embeds.length;
let equal = this.id === message.id &&
this.author.id === message.author.id &&
this.content === message.content &&
this.tts === message.tts &&
this.nonce === message.nonce &&
this.embeds.length === message.embeds.length &&
this.attachments.length === message.attachments.length;
let equal =
this.id === message.id &&
this.author.id === message.author.id &&
this.content === message.content &&
this.tts === message.tts &&
this.nonce === message.nonce &&
this.embeds.length === message.embeds.length &&
this.attachments.length === message.attachments.length;
if (equal && rawData) {
equal = this.mentions.everyone === message.mentions.everyone &&
equal =
this.mentions.everyone === message.mentions.everyone &&
this.createdTimestamp === new Date(rawData.timestamp).getTime() &&
this.editedTimestamp === new Date(rawData.edited_timestamp).getTime();
}

View File

@@ -1,7 +1,7 @@
'use strict';
const Util = require('../util/Util');
const { RangeError } = require('../errors');
const Util = require('../util/Util');
/**
* Represents an embed in a message (image/video preview, rich embed, etc.)
@@ -11,7 +11,7 @@ class MessageEmbed {
this.setup(data);
}
setup(data) { // eslint-disable-line complexity
setup(data) {
/**
* The type of this embed, either:
* * `rich` - a rich embed
@@ -79,12 +79,14 @@ class MessageEmbed {
* The thumbnail of this embed (if there is one)
* @type {?MessageEmbedThumbnail}
*/
this.thumbnail = data.thumbnail ? {
url: data.thumbnail.url,
proxyURL: data.thumbnail.proxyURL || data.thumbnail.proxy_url,
height: data.thumbnail.height,
width: data.thumbnail.width,
} : null;
this.thumbnail = data.thumbnail
? {
url: data.thumbnail.url,
proxyURL: data.thumbnail.proxyURL || data.thumbnail.proxy_url,
height: data.thumbnail.height,
width: data.thumbnail.width,
}
: null;
/**
* @typedef {Object} MessageEmbedImage
@@ -98,12 +100,14 @@ class MessageEmbed {
* The image of this embed, if there is one
* @type {?MessageEmbedImage}
*/
this.image = data.image ? {
url: data.image.url,
proxyURL: data.image.proxyURL || data.image.proxy_url,
height: data.image.height,
width: data.image.width,
} : null;
this.image = data.image
? {
url: data.image.url,
proxyURL: data.image.proxyURL || data.image.proxy_url,
height: data.image.height,
width: data.image.width,
}
: null;
/**
* @typedef {Object} MessageEmbedVideo
@@ -118,12 +122,14 @@ class MessageEmbed {
* @type {?MessageEmbedVideo}
* @readonly
*/
this.video = data.video ? {
url: data.video.url,
proxyURL: data.video.proxyURL || data.video.proxy_url,
height: data.video.height,
width: data.video.width,
} : null;
this.video = data.video
? {
url: data.video.url,
proxyURL: data.video.proxyURL || data.video.proxy_url,
height: data.video.height,
width: data.video.width,
}
: null;
/**
* @typedef {Object} MessageEmbedAuthor
@@ -137,12 +143,14 @@ class MessageEmbed {
* The author of this embed (if there is one)
* @type {?MessageEmbedAuthor}
*/
this.author = data.author ? {
name: data.author.name,
url: data.author.url,
iconURL: data.author.iconURL || data.author.icon_url,
proxyIconURL: data.author.proxyIconURL || data.author.proxy_icon_url,
} : null;
this.author = data.author
? {
name: data.author.name,
url: data.author.url,
iconURL: data.author.iconURL || data.author.icon_url,
proxyIconURL: data.author.proxyIconURL || data.author.proxy_icon_url,
}
: null;
/**
* @typedef {Object} MessageEmbedProvider
@@ -154,10 +162,12 @@ class MessageEmbed {
* The provider of this embed (if there is one)
* @type {?MessageEmbedProvider}
*/
this.provider = data.provider ? {
name: data.provider.name,
url: data.provider.name,
} : null;
this.provider = data.provider
? {
name: data.provider.name,
url: data.provider.name,
}
: null;
/**
* @typedef {Object} MessageEmbedFooter
@@ -170,11 +180,13 @@ class MessageEmbed {
* The footer of this embed
* @type {?MessageEmbedFooter}
*/
this.footer = data.footer ? {
text: data.footer.text,
iconURL: data.footer.iconURL || data.footer.icon_url,
proxyIconURL: data.footer.proxyIconURL || data.footer.proxy_icon_url,
} : null;
this.footer = data.footer
? {
text: data.footer.text,
iconURL: data.footer.iconURL || data.footer.icon_url,
proxyIconURL: data.footer.proxyIconURL || data.footer.proxy_icon_url,
}
: null;
/**
* The files of this embed
@@ -210,9 +222,11 @@ class MessageEmbed {
return (
(this.title ? this.title.length : 0) +
(this.description ? this.description.length : 0) +
(this.fields.length >= 1 ? this.fields.reduce((prev, curr) =>
prev + curr.name.length + curr.value.length, 0) : 0) +
(this.footer ? this.footer.text.length : 0));
(this.fields.length >= 1
? this.fields.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0)
: 0) +
(this.footer ? this.footer.text.length : 0)
);
}
/**
@@ -371,15 +385,19 @@ class MessageEmbed {
fields: this.fields,
thumbnail: this.thumbnail,
image: this.image,
author: this.author ? {
name: this.author.name,
url: this.author.url,
icon_url: this.author.iconURL,
} : null,
footer: this.footer ? {
text: this.footer.text,
icon_url: this.footer.iconURL,
} : null,
author: this.author
? {
name: this.author.name,
url: this.author.url,
icon_url: this.author.iconURL,
}
: null,
footer: this.footer
? {
text: this.footer.text,
icon_url: this.footer.iconURL,
}
: null,
};
}
@@ -399,11 +417,11 @@ class MessageEmbed {
}
/**
* @typedef {Object} EmbedFieldData
* @property {StringResolvable} name The name of this field
* @property {StringResolvable} value The value of this field
* @property {boolean} [inline=false] If this field will be displayed inline
*/
* @typedef {Object} EmbedFieldData
* @property {StringResolvable} name The name of this field
* @property {StringResolvable} value The value of this field
* @property {boolean} [inline] If this field will be displayed inline
*/
/**
* Normalizes field input and resolves strings.
@@ -411,13 +429,15 @@ class MessageEmbed {
* @returns {EmbedField[]}
*/
static normalizeFields(...fields) {
return fields.flat(2).map(field =>
this.normalizeField(
field && field.name,
field && field.value,
field && typeof field.inline === 'boolean' ? field.inline : false,
),
);
return fields
.flat(2)
.map(field =>
this.normalizeField(
field && field.name,
field && field.value,
field && typeof field.inline === 'boolean' ? field.inline : false,
),
);
}
}

View File

@@ -1,9 +1,9 @@
'use strict';
const Collection = require('../util/Collection');
const Util = require('../util/Util');
const GuildMember = require('./GuildMember');
const Collection = require('../util/Collection');
const { ChannelTypes } = require('../util/Constants');
const Util = require('../util/Util');
/**
* Keeps track of mentions in a {@link Message}.

View File

@@ -1,9 +1,9 @@
'use strict';
const GuildEmoji = require('./GuildEmoji');
const Util = require('../util/Util');
const ReactionEmoji = require('./ReactionEmoji');
const ReactionUserManager = require('../managers/ReactionUserManager');
const Util = require('../util/Util');
/**
* Represents a reaction to a message.
@@ -59,7 +59,10 @@ class MessageReaction {
* @returns {Promise<MessageReaction>}
*/
async remove() {
await this.client.api.channels(this.message.channel.id).messages(this.message.id).reactions(this._emoji.identifier)
await this.client.api
.channels(this.message.channel.id)
.messages(this.message.id)
.reactions(this._emoji.identifier)
.delete();
return this;
}

View File

@@ -1,9 +1,9 @@
'use strict';
const Role = require('./Role');
const { TypeError } = require('../errors');
const Permissions = require('../util/Permissions');
const Util = require('../util/Util');
const { TypeError } = require('../errors');
/**
* Represents a permission overwrite for a role or member in a guild channel.
@@ -70,8 +70,12 @@ class PermissionOverwrites {
update(options, reason) {
const { allow, deny } = this.constructor.resolveOverwriteOptions(options, this);
return this.channel.client.api.channels(this.channel.id).permissions[this.id]
.put({ data: { id: this.id, type: this.type, allow: allow.bitfield, deny: deny.bitfield }, reason })
return this.channel.client.api
.channels(this.channel.id)
.permissions[this.id].put({
data: { id: this.id, type: this.type, allow: allow.bitfield, deny: deny.bitfield },
reason,
})
.then(() => this);
}
@@ -81,9 +85,7 @@ class PermissionOverwrites {
* @returns {Promise<PermissionOverwrites>}
*/
delete(reason) {
return this.channel.client.api.channels[this.channel.id].permissions[this.id]
.delete({ reason })
.then(() => this);
return this.channel.client.api.channels[this.channel.id].permissions[this.id].delete({ reason }).then(() => this);
}
toJSON() {
@@ -168,10 +170,7 @@ class PermissionOverwrites {
static resolve(overwrite, guild) {
if (overwrite instanceof this) return overwrite.toJSON();
if (typeof overwrite.id === 'string' && ['role', 'member'].includes(overwrite.type)) {
return { ...overwrite,
allow: Permissions.resolve(overwrite.allow),
deny: Permissions.resolve(overwrite.deny),
};
return { ...overwrite, allow: Permissions.resolve(overwrite.allow), deny: Permissions.resolve(overwrite.deny) };
}
const userOrRole = guild.roles.resolve(overwrite.id) || guild.client.users.resolve(overwrite.id);

View File

@@ -1,9 +1,9 @@
'use strict';
const Util = require('../util/Util');
const Emoji = require('./Emoji');
const ActivityFlags = require('../util/ActivityFlags');
const { ActivityTypes } = require('../util/Constants');
const Emoji = require('./Emoji');
const Util = require('../util/Util');
/**
* Activity sent in a message.
@@ -121,14 +121,15 @@ class Presence {
* @returns {boolean}
*/
equals(presence) {
return this === presence || (
presence &&
this.status === presence.status &&
this.activities.length === presence.activities.length &&
this.activities.every((activity, index) => activity.equals(presence.activities[index])) &&
this.clientStatus.web === presence.clientStatus.web &&
this.clientStatus.mobile === presence.clientStatus.mobile &&
this.clientStatus.desktop === presence.clientStatus.desktop
return (
this === presence ||
(presence &&
this.status === presence.status &&
this.activities.length === presence.activities.length &&
this.activities.every((activity, index) => activity.equals(presence.activities[index])) &&
this.clientStatus.web === presence.clientStatus.web &&
this.clientStatus.mobile === presence.clientStatus.mobile &&
this.clientStatus.desktop === presence.clientStatus.desktop)
);
}
@@ -186,10 +187,12 @@ class Activity {
* @prop {?Date} start When the activity started
* @prop {?Date} end When the activity will end
*/
this.timestamps = data.timestamps ? {
start: data.timestamps.start ? new Date(Number(data.timestamps.start)) : null,
end: data.timestamps.end ? new Date(Number(data.timestamps.end)) : null,
} : null;
this.timestamps = data.timestamps
? {
start: data.timestamps.start ? new Date(Number(data.timestamps.start)) : null,
end: data.timestamps.end ? new Date(Number(data.timestamps.end)) : null,
}
: null;
/**
* Party of the activity
@@ -232,11 +235,9 @@ class Activity {
* @returns {boolean}
*/
equals(activity) {
return this === activity || (
activity &&
this.name === activity.name &&
this.type === activity.type &&
this.url === activity.url
return (
this === activity ||
(activity && this.name === activity.name && this.type === activity.type && this.url === activity.url)
);
}
@@ -303,8 +304,10 @@ class RichPresenceAssets {
*/
smallImageURL({ format, size } = {}) {
if (!this.smallImage) return null;
return this.activity.presence.client.rest.cdn
.AppAsset(this.activity.applicationID, this.smallImage, { format, size });
return this.activity.presence.client.rest.cdn.AppAsset(this.activity.applicationID, this.smallImage, {
format,
size,
});
}
/**
@@ -321,8 +324,10 @@ class RichPresenceAssets {
} else if (/^twitch:/.test(this.largeImage)) {
return `https://static-cdn.jtvnw.net/previews-ttv/live_user_${this.largeImage.slice(7)}.png`;
}
return this.activity.presence.client.rest.cdn
.AppAsset(this.activity.applicationID, this.largeImage, { format, size });
return this.activity.presence.client.rest.cdn.AppAsset(this.activity.applicationID, this.largeImage, {
format,
size,
});
}
}

View File

@@ -118,8 +118,7 @@ class ReactionCollector extends Collector {
* @param {MessageReaction} reaction The reaction that was removed
* @param {User} user The user that removed the reaction
*/
if (this.collected.has(ReactionCollector.key(reaction)) &&
this.users.has(user.id)) {
if (this.collected.has(ReactionCollector.key(reaction)) && this.users.has(user.id)) {
this.emit('remove', reaction, user);
}
return reaction.count ? null : ReactionCollector.key(reaction);

View File

@@ -1,7 +1,7 @@
'use strict';
const Util = require('../util/Util');
const Emoji = require('./Emoji');
const Util = require('../util/Util');
/**
* Represents a limited emoji set used for both custom and unicode emojis. Custom emojis

View File

@@ -1,10 +1,10 @@
'use strict';
const Snowflake = require('../util/Snowflake');
const Permissions = require('../util/Permissions');
const Util = require('../util/Util');
const Base = require('./Base');
const { Error, TypeError } = require('../errors');
const Permissions = require('../util/Permissions');
const Snowflake = require('../util/Snowflake');
const Util = require('../util/Util');
/**
* Represents a role on Discord.
@@ -180,25 +180,31 @@ class Role extends Base {
if (typeof data.permissions !== 'undefined') data.permissions = Permissions.resolve(data.permissions);
else data.permissions = this.permissions.bitfield;
if (typeof data.position !== 'undefined') {
await Util.setPosition(this, data.position, false, this.guild._sortedRoles(),
this.client.api.guilds(this.guild.id).roles, reason)
.then(updatedRoles => {
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: updatedRoles,
});
await Util.setPosition(
this,
data.position,
false,
this.guild._sortedRoles(),
this.client.api.guilds(this.guild.id).roles,
reason,
).then(updatedRoles => {
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: updatedRoles,
});
});
}
return this.client.api.guilds[this.guild.id].roles[this.id].patch({
data: {
name: data.name || this.name,
color: data.color !== null ? Util.resolveColor(data.color || this.color) : null,
hoist: typeof data.hoist !== 'undefined' ? data.hoist : this.hoist,
permissions: data.permissions,
mentionable: typeof data.mentionable !== 'undefined' ? data.mentionable : this.mentionable,
},
reason,
})
return this.client.api.guilds[this.guild.id].roles[this.id]
.patch({
data: {
name: data.name || this.name,
color: data.color !== null ? Util.resolveColor(data.color || this.color) : null,
hoist: typeof data.hoist !== 'undefined' ? data.hoist : this.hoist,
permissions: data.permissions,
mentionable: typeof data.mentionable !== 'undefined' ? data.mentionable : this.mentionable,
},
reason,
})
.then(role => {
const clone = this._clone();
clone._patch(role);
@@ -312,15 +318,20 @@ class Role extends Base {
* .catch(console.error);
*/
setPosition(position, { relative, reason } = {}) {
return Util.setPosition(this, position, relative,
this.guild._sortedRoles(), this.client.api.guilds(this.guild.id).roles, reason)
.then(updatedRoles => {
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: updatedRoles,
});
return this;
return Util.setPosition(
this,
position,
relative,
this.guild._sortedRoles(),
this.client.api.guilds(this.guild.id).roles,
reason,
).then(updatedRoles => {
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: updatedRoles,
});
return this;
});
}
/**
@@ -334,11 +345,10 @@ class Role extends Base {
* .catch(console.error);
*/
delete(reason) {
return this.client.api.guilds[this.guild.id].roles[this.id].delete({ reason })
.then(() => {
this.client.actions.GuildRoleDelete.handle({ guild_id: this.guild.id, role_id: this.id });
return this;
});
return this.client.api.guilds[this.guild.id].roles[this.id].delete({ reason }).then(() => {
this.client.actions.GuildRoleDelete.handle({ guild_id: this.guild.id, role_id: this.id });
return this;
});
}
/**
@@ -349,14 +359,16 @@ class Role extends Base {
* @returns {boolean}
*/
equals(role) {
return role &&
return (
role &&
this.id === role.id &&
this.name === role.name &&
this.color === role.color &&
this.hoist === role.hoist &&
this.position === role.position &&
this.permissions.bitfield === role.permissions.bitfield &&
this.managed === role.managed;
this.managed === role.managed
);
}
/**

View File

@@ -1,9 +1,9 @@
'use strict';
const Snowflake = require('../util/Snowflake');
const Collection = require('../util/Collection');
const Base = require('./Base');
const TeamMember = require('./TeamMember');
const Collection = require('../util/Collection');
const Snowflake = require('../util/Snowflake');
/**
* Represents a Client OAuth2 Application Team.

View File

@@ -3,9 +3,9 @@
const GuildChannel = require('./GuildChannel');
const Webhook = require('./Webhook');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const MessageManager = require('../managers/MessageManager');
const Collection = require('../util/Collection');
const DataResolver = require('../util/DataResolver');
const MessageManager = require('../managers/MessageManager');
/**
* Represents a guild text channel on Discord.
@@ -121,9 +121,15 @@ class TextChannel extends GuildChannel {
if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await DataResolver.resolveImage(avatar);
}
return this.client.api.channels[this.id].webhooks.post({ data: {
name, avatar,
}, reason }).then(data => new Webhook(this.client, data));
return this.client.api.channels[this.id].webhooks
.post({
data: {
name,
avatar,
},
reason,
})
.then(data => new Webhook(this.client, data));
}
// These are here only for documentation purposes - they are implemented by TextBasedChannel

View File

@@ -1,10 +1,10 @@
'use strict';
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Presence } = require('./Presence');
const Snowflake = require('../util/Snowflake');
const Base = require('./Base');
const { Presence } = require('./Presence');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Error } = require('../errors');
const Snowflake = require('../util/Snowflake');
/**
* Represents a user on Discord.
@@ -219,9 +219,11 @@ class User extends Base {
async createDM() {
const { dmChannel } = this;
if (dmChannel && !dmChannel.partial) return dmChannel;
const data = await this.client.api.users(this.client.user.id).channels.post({ data: {
recipient_id: this.id,
} });
const data = await this.client.api.users(this.client.user.id).channels.post({
data: {
recipient_id: this.id,
},
});
return this.client.actions.ChannelCreate.handle(data).channel;
}
@@ -243,7 +245,8 @@ class User extends Base {
* @returns {boolean}
*/
equals(user) {
let equal = user &&
let equal =
user &&
this.id === user.id &&
this.username === user.username &&
this.discriminator === user.discriminator &&
@@ -272,13 +275,16 @@ class User extends Base {
}
toJSON(...props) {
const json = super.toJSON({
createdTimestamp: true,
defaultAvatarURL: true,
tag: true,
lastMessage: false,
lastMessageID: false,
}, ...props);
const json = super.toJSON(
{
createdTimestamp: true,
defaultAvatarURL: true,
tag: true,
lastMessage: false,
lastMessageID: false,
},
...props,
);
json.avatarURL = this.avatarURL();
json.displayAvatarURL = this.displayAvatarURL();
return json;

View File

@@ -1,10 +1,10 @@
'use strict';
const GuildChannel = require('./GuildChannel');
const { Error } = require('../errors');
const Collection = require('../util/Collection');
const { browser } = require('../util/Constants');
const Permissions = require('../util/Permissions');
const Collection = require('../util/Collection');
const { Error } = require('../errors');
/**
* Represents a guild voice channel on Discord.

View File

@@ -1,8 +1,8 @@
'use strict';
const Base = require('./Base');
const { browser } = require('../util/Constants');
const { Error, TypeError } = require('../errors');
const { browser } = require('../util/Constants');
/**
* Represents the voice state for a Guild Member.
@@ -119,9 +119,7 @@ class VoiceState extends Base {
* @readonly
*/
get speaking() {
return this.channel && this.channel.connection ?
Boolean(this.channel.connection._speaking.get(this.id)) :
null;
return this.channel && this.channel.connection ? Boolean(this.channel.connection._speaking.get(this.id)) : null;
}
/**
@@ -161,9 +159,9 @@ class VoiceState extends Base {
* @returns {Promise<GuildMember>}
*/
setChannel(channel, reason) {
return this.member ?
this.member.edit({ channel }, reason) :
Promise.reject(new Error('VOICE_STATE_UNCACHED_MEMBER'));
return this.member
? this.member.edit({ channel }, reason)
: Promise.reject(new Error('VOICE_STATE_UNCACHED_MEMBER'));
}
/**

View File

@@ -1,10 +1,10 @@
'use strict';
const APIMessage = require('./APIMessage');
const Channel = require('./Channel');
const { WebhookTypes } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const Snowflake = require('../util/Snowflake');
const Channel = require('./Channel');
const APIMessage = require('./APIMessage');
/**
* Represents a webhook.
@@ -149,15 +149,19 @@ class Webhook {
}
const { data, files } = await apiMessage.resolveFiles();
return this.client.api.webhooks(this.id, this.token).post({
data, files,
query: { wait: true },
auth: false,
}).then(d => {
const channel = this.client.channels ? this.client.channels.cache.get(d.channel_id) : undefined;
if (!channel) return d;
return channel.messages.add(d, false);
});
return this.client.api
.webhooks(this.id, this.token)
.post({
data,
files,
query: { wait: true },
auth: false,
})
.then(d => {
const channel = this.client.channels ? this.client.channels.cache.get(d.channel_id) : undefined;
if (!channel) return d;
return channel.messages.add(d, false);
});
}
/**
@@ -178,11 +182,14 @@ class Webhook {
* }).catch(console.error);
*/
sendSlackMessage(body) {
return this.client.api.webhooks(this.id, this.token).slack.post({
query: { wait: true },
auth: false,
data: body,
}).then(data => data.toString() === 'ok');
return this.client.api
.webhooks(this.id, this.token)
.slack.post({
query: { wait: true },
auth: false,
data: body,
})
.then(data => data.toString() === 'ok');
}
/**
@@ -195,7 +202,7 @@ class Webhook {
* @returns {Promise<Webhook>}
*/
async edit({ name = this.name, avatar, channel }, reason) {
if (avatar && (typeof avatar === 'string' && !avatar.startsWith('data:'))) {
if (avatar && typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await DataResolver.resolveImage(avatar);
}
if (channel) channel = channel instanceof Channel ? channel.id : channel;
@@ -256,17 +263,8 @@ class Webhook {
}
static applyToClass(structure) {
for (const prop of [
'send',
'sendSlackMessage',
'edit',
'delete',
'createdTimestamp',
'createdAt',
'url',
]) {
Object.defineProperty(structure.prototype, prop,
Object.getOwnPropertyDescriptor(Webhook.prototype, prop));
for (const prop of ['send', 'sendSlackMessage', 'edit', 'delete', 'createdTimestamp', 'createdAt', 'url']) {
Object.defineProperty(structure.prototype, prop, Object.getOwnPropertyDescriptor(Webhook.prototype, prop));
}
}
}

View File

@@ -1,8 +1,8 @@
'use strict';
const EventEmitter = require('events');
const Collection = require('../../util/Collection');
const Util = require('../../util/Util');
const EventEmitter = require('events');
/**
* Filter to be applied to the collector.

View File

@@ -1,10 +1,11 @@
'use strict';
/* eslint-disable import/order */
const MessageCollector = require('../MessageCollector');
const APIMessage = require('../APIMessage');
const Snowflake = require('../../util/Snowflake');
const Collection = require('../../util/Collection');
const { RangeError, TypeError } = require('../../errors');
const APIMessage = require('../APIMessage');
/**
* Interface for classes that have text-channel-like features.
@@ -144,7 +145,8 @@ class TextBasedChannel {
}
const { data, files } = await apiMessage.resolveFiles();
return this.client.api.channels[this.id].messages.post({ data, files })
return this.client.api.channels[this.id].messages
.post({ data, files })
.then(d => this.client.actions.MessageCreate.handle(d).message);
}
@@ -299,23 +301,36 @@ class TextBasedChannel {
if (Array.isArray(messages) || messages instanceof Collection) {
let messageIDs = messages instanceof Collection ? messages.keyArray() : messages.map(m => m.id || m);
if (filterOld) {
messageIDs = messageIDs.filter(id =>
Date.now() - Snowflake.deconstruct(id).date.getTime() < 1209600000,
);
messageIDs = messageIDs.filter(id => Date.now() - Snowflake.deconstruct(id).date.getTime() < 1209600000);
}
if (messageIDs.length === 0) return new Collection();
if (messageIDs.length === 1) {
await this.client.api.channels(this.id).messages(messageIDs[0]).delete();
const message = this.client.actions.MessageDelete.getMessage({
message_id: messageIDs[0],
}, this);
await this.client.api
.channels(this.id)
.messages(messageIDs[0])
.delete();
const message = this.client.actions.MessageDelete.getMessage(
{
message_id: messageIDs[0],
},
this,
);
return message ? new Collection([[message.id, message]]) : new Collection();
}
await this.client.api.channels[this.id].messages['bulk-delete']
.post({ data: { messages: messageIDs } });
return messageIDs.reduce((col, id) => col.set(id, this.client.actions.MessageDeleteBulk.getMessage({
message_id: id,
}, this)), new Collection());
await this.client.api.channels[this.id].messages['bulk-delete'].post({ data: { messages: messageIDs } });
return messageIDs.reduce(
(col, id) =>
col.set(
id,
this.client.actions.MessageDeleteBulk.getMessage(
{
message_id: id,
},
this,
),
),
new Collection(),
);
}
if (!isNaN(messages)) {
const msgs = await this.messages.fetch({ limit: messages });
@@ -341,8 +356,11 @@ class TextBasedChannel {
}
for (const prop of props) {
if (ignore.includes(prop)) continue;
Object.defineProperty(structure.prototype, prop,
Object.getOwnPropertyDescriptor(TextBasedChannel.prototype, prop));
Object.defineProperty(
structure.prototype,
prop,
Object.getOwnPropertyDescriptor(TextBasedChannel.prototype, prop),
);
}
}
}