refactor: make use of destructuring for Constants (#1942)

This commit is contained in:
SpaceEEC
2017-09-16 20:31:36 +02:00
committed by Crawl
parent 25ece1882b
commit ec4c98704f
66 changed files with 262 additions and 262 deletions

View File

@@ -1,7 +1,7 @@
const EventEmitter = require('events');
const RESTManager = require('../rest/RESTManager');
const Util = require('../util/Util');
const Constants = require('../util/Constants');
const { DefaultOptions } = require('../util/Constants');
/**
* The base class for all clients.
@@ -15,7 +15,7 @@ class BaseClient extends EventEmitter {
* The options the client was instantiated with
* @type {ClientOptions}
*/
this.options = Util.mergeDefault(Constants.DefaultOptions, options);
this.options = Util.mergeDefault(DefaultOptions, options);
/**
* The REST manager of the client

View File

@@ -17,7 +17,7 @@ const ChannelStore = require('../stores/ChannelStore');
const GuildStore = require('../stores/GuildStore');
const ClientPresenceStore = require('../stores/ClientPresenceStore');
const EmojiStore = require('../stores/EmojiStore');
const Constants = require('../util/Constants');
const { Events } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const { Error, TypeError, RangeError } = require('../errors');
@@ -334,7 +334,7 @@ class Client extends BaseClient {
throw new TypeError('CLIENT_INVALID_OPTION', 'Lifetime', 'a number');
}
if (lifetime <= 0) {
this.emit(Constants.Events.DEBUG, 'Didn\'t sweep messages - lifetime is unlimited');
this.emit(Events.DEBUG, 'Didn\'t sweep messages - lifetime is unlimited');
return -1;
}
@@ -355,7 +355,7 @@ class Client extends BaseClient {
}
}
this.emit(Constants.Events.DEBUG,
this.emit(Events.DEBUG,
`Swept ${messages} messages older than ${lifetime} seconds in ${channels} text-based channels`);
return messages;
}

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { Events, Status } = require('../util/Constants');
const { Error } = require('../errors');
/**
@@ -25,7 +25,7 @@ class ClientManager {
* @type {number}
*/
get status() {
return this.connection ? this.connection.status : Constants.Status.IDLE;
return this.connection ? this.connection.status : Status.IDLE;
}
/**
@@ -35,19 +35,19 @@ class ClientManager {
* @param {Function} reject Function to run when connection fails
*/
connectToWebSocket(token, resolve, reject) {
this.client.emit(Constants.Events.DEBUG, `Authenticated using token ${token}`);
this.client.emit(Events.DEBUG, `Authenticated using token ${token}`);
this.client.token = token;
const timeout = this.client.setTimeout(() => reject(new Error('TOKEN_INVALID')), 1000 * 300);
this.client.api.gateway.get().then(res => {
const gateway = `${res.url}/`;
this.client.emit(Constants.Events.DEBUG, `Using gateway ${gateway}`);
this.client.emit(Events.DEBUG, `Using gateway ${gateway}`);
this.client.ws.connect(gateway);
this.client.ws.connection.once('close', event => {
if (event.code === 4004) reject(new Error('TOKEN_INVALID'));
if (event.code === 4010) reject(new Error('SHARDING_INVALID'));
if (event.code === 4011) reject(new Error('SHARDING_REQUIRED'));
});
this.client.once(Constants.Events.READY, () => {
this.client.once(Events.READY, () => {
resolve(token);
this.client.clearTimeout(timeout);
});

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class ChannelCreateAction extends Action {
handle(data) {
@@ -7,7 +7,7 @@ class ChannelCreateAction extends Action {
const existing = client.channels.has(data.id);
const channel = client.channels.create(data);
if (!existing && channel) {
client.emit(Constants.Events.CHANNEL_CREATE, channel);
client.emit(Events.CHANNEL_CREATE, channel);
}
return { channel };
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class ChannelDeleteAction extends Action {
constructor(client) {
@@ -13,7 +13,7 @@ class ChannelDeleteAction extends Action {
if (channel) {
client.channels.remove(channel.id);
client.emit(Constants.Events.CHANNEL_DELETE, channel);
client.emit(Events.CHANNEL_DELETE, channel);
}
return { channel };

View File

@@ -1,12 +1,12 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildBanRemove extends Action {
handle(data) {
const client = this.client;
const guild = client.guilds.get(data.guild_id);
const user = client.users.create(data.user);
if (guild && user) client.emit(Constants.Events.GUILD_BAN_REMOVE, guild, user);
if (guild && user) client.emit(Events.GUILD_BAN_REMOVE, guild, user);
}
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildDeleteAction extends Action {
constructor(client) {
@@ -19,7 +19,7 @@ class GuildDeleteAction extends Action {
if (guild.available && data.unavailable) {
// Guild is unavailable
guild.available = false;
client.emit(Constants.Events.GUILD_UNAVAILABLE, guild);
client.emit(Events.GUILD_UNAVAILABLE, guild);
// Stops the GuildDelete packet thinking a guild was actually deleted,
// handles emitting of event itself
@@ -30,7 +30,7 @@ class GuildDeleteAction extends Action {
// Delete guild
client.guilds.remove(guild.id);
client.emit(Constants.Events.GUILD_DELETE, guild);
client.emit(Events.GUILD_DELETE, guild);
this.deleted.set(guild.id, guild);
this.scheduleForDeletion(guild.id);
} else {

View File

@@ -1,10 +1,10 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildEmojiCreateAction extends Action {
handle(guild, createdEmoji) {
const emoji = guild.emojis.create(createdEmoji);
this.client.emit(Constants.Events.GUILD_EMOJI_CREATE, emoji);
this.client.emit(Events.GUILD_EMOJI_CREATE, emoji);
return { emoji };
}
}

View File

@@ -1,10 +1,10 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildEmojiDeleteAction extends Action {
handle(emoji) {
emoji.guild.emojis.remove(emoji.id);
this.client.emit(Constants.Events.GUILD_EMOJI_DELETE, emoji);
this.client.emit(Events.GUILD_EMOJI_DELETE, emoji);
return { emoji };
}
}

View File

@@ -1,10 +1,10 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildEmojiUpdateAction extends Action {
handle(current, data) {
const old = current._update(data);
this.client.emit(Constants.Events.GUILD_EMOJI_UPDATE, old, current);
this.client.emit(Events.GUILD_EMOJI_UPDATE, old, current);
return { emoji: current };
}
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events, Status } = require('../../util/Constants');
class GuildMemberRemoveAction extends Action {
handle(data) {
@@ -11,7 +11,7 @@ class GuildMemberRemoveAction extends Action {
if (member) {
guild.memberCount--;
guild.members.remove(member.id);
if (client.status === Constants.Status.READY) client.emit(Constants.Events.GUILD_MEMBER_REMOVE, member);
if (client.status === Status.READY) client.emit(Events.GUILD_MEMBER_REMOVE, member);
}
}
return { guild, member };

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildRoleCreate extends Action {
handle(data) {
@@ -9,7 +9,7 @@ class GuildRoleCreate extends Action {
if (guild) {
const already = guild.roles.has(data.role.id);
role = guild.roles.create(data.role);
if (!already) client.emit(Constants.Events.GUILD_ROLE_CREATE, role);
if (!already) client.emit(Events.GUILD_ROLE_CREATE, role);
}
return { role };
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildRoleDeleteAction extends Action {
handle(data) {
@@ -11,7 +11,7 @@ class GuildRoleDeleteAction extends Action {
role = guild.roles.get(data.role_id);
if (role) {
guild.roles.remove(data.role_id);
client.emit(Constants.Events.GUILD_ROLE_DELETE, role);
client.emit(Events.GUILD_ROLE_DELETE, role);
}
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildRoleUpdateAction extends Action {
handle(data) {
@@ -12,7 +12,7 @@ class GuildRoleUpdateAction extends Action {
const role = guild.roles.get(data.role.id);
if (role) {
old = role._update(data.role);
client.emit(Constants.Events.GUILD_ROLE_UPDATE, old, role);
client.emit(Events.GUILD_ROLE_UPDATE, old, role);
}
return {

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class GuildUpdateAction extends Action {
handle(data) {
@@ -8,7 +8,7 @@ class GuildUpdateAction extends Action {
const guild = client.guilds.get(data.id);
if (guild) {
const old = guild._update(data);
client.emit(Constants.Events.GUILD_UPDATE, old, guild);
client.emit(Events.GUILD_UPDATE, old, guild);
return {
old,
updated: guild,

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class MessageCreateAction extends Action {
handle(data) {
@@ -22,7 +22,7 @@ class MessageCreateAction extends Action {
member.lastMessage = message;
}
client.emit(Constants.Events.MESSAGE_CREATE, message);
client.emit(Events.MESSAGE_CREATE, message);
return { message };
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class MessageDeleteAction extends Action {
handle(data) {
@@ -11,7 +11,7 @@ class MessageDeleteAction extends Action {
message = channel.messages.get(data.id);
if (message) {
channel.messages.delete(message.id);
client.emit(Constants.Events.MESSAGE_DELETE, message);
client.emit(Events.MESSAGE_DELETE, message);
}
}

View File

@@ -1,6 +1,6 @@
const Action = require('./Action');
const Collection = require('../../util/Collection');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class MessageDeleteBulkAction extends Action {
handle(data) {
@@ -15,7 +15,7 @@ class MessageDeleteBulkAction extends Action {
if (message) messages.set(message.id, message);
}
if (messages.size > 0) client.emit(Constants.Events.MESSAGE_BULK_DELETE, messages);
if (messages.size > 0) client.emit(Events.MESSAGE_BULK_DELETE, messages);
return { messages };
}
return {};

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
/*
{ user_id: 'id',
@@ -24,7 +24,7 @@ class MessageReactionRemove extends Action {
const reaction = message.reactions.get(emojiID);
if (!reaction) return false;
reaction._remove(user);
this.client.emit(Constants.Events.MESSAGE_REACTION_REMOVE, reaction, user);
this.client.emit(Events.MESSAGE_REACTION_REMOVE, reaction, user);
return { message, reaction, user };
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class MessageReactionRemoveAll extends Action {
handle(data) {
@@ -10,7 +10,7 @@ class MessageReactionRemoveAll extends Action {
if (!message) return false;
message.reactions.clear();
this.client.emit(Constants.Events.MESSAGE_REACTION_REMOVE_ALL, message);
this.client.emit(Events.MESSAGE_REACTION_REMOVE_ALL, message);
return { message };
}

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class UserNoteUpdateAction extends Action {
handle(data) {
@@ -10,7 +10,7 @@ class UserNoteUpdateAction extends Action {
client.user.notes.set(data.id, note);
client.emit(Constants.Events.USER_NOTE_UPDATE, data.id, oldNote, note);
client.emit(Events.USER_NOTE_UPDATE, data.id, oldNote, note);
return {
old: oldNote,

View File

@@ -1,5 +1,5 @@
const Action = require('./Action');
const Constants = require('../../util/Constants');
const { Events } = require('../../util/Constants');
class UserUpdateAction extends Action {
handle(data) {
@@ -14,7 +14,7 @@ class UserUpdateAction extends Action {
}
const oldUser = client.user._update(data);
client.emit(Constants.Events.USER_UPDATE, oldUser, client.user);
client.emit(Events.USER_UPDATE, oldUser, client.user);
return {
old: oldUser,
updated: client.user,

View File

@@ -1,5 +1,5 @@
const Collection = require('../../util/Collection');
const Constants = require('../../util/Constants');
const { VoiceStatus } = require('../../util/Constants');
const VoiceConnection = require('./VoiceConnection');
const { Error } = require('../../errors');
@@ -33,7 +33,7 @@ class ClientVoiceManager {
onVoiceStateUpdate({ guild_id, session_id, channel_id }) {
const connection = this.connections.get(guild_id);
if (!connection) return;
if (!channel_id && connection.status !== Constants.VoiceStatus.DISCONNECTED) {
if (!channel_id && connection.status !== VoiceStatus.DISCONNECTED) {
connection._disconnect();
return;
}

View File

@@ -1,7 +1,7 @@
const VoiceWebSocket = require('./VoiceWebSocket');
const VoiceUDP = require('./VoiceUDPClient');
const Util = require('../../util/Util');
const Constants = require('../../util/Constants');
const { OPCodes, VoiceOPCodes, VoiceStatus } = require('../../util/Constants');
const AudioPlayer = require('./player/AudioPlayer');
const VoiceReceiver = require('./receiver/VoiceReceiver');
const EventEmitter = require('events');
@@ -56,7 +56,7 @@ class VoiceConnection extends EventEmitter {
* The current status of the voice connection
* @type {VoiceStatus}
*/
this.status = Constants.VoiceStatus.AUTHENTICATING;
this.status = VoiceStatus.AUTHENTICATING;
/**
* Whether we're currently transmitting audio
@@ -134,10 +134,10 @@ class VoiceConnection extends EventEmitter {
*/
setSpeaking(value) {
if (this.speaking === value) return;
if (this.status !== Constants.VoiceStatus.CONNECTED) return;
if (this.status !== VoiceStatus.CONNECTED) return;
this.speaking = value;
this.sockets.ws.sendPacket({
op: Constants.VoiceOPCodes.SPEAKING,
op: VoiceOPCodes.SPEAKING,
d: {
speaking: true,
delay: 0,
@@ -161,7 +161,7 @@ class VoiceConnection extends EventEmitter {
}, options);
this.client.ws.send({
op: Constants.OPCodes.VOICE_STATE_UPDATE,
op: OPCodes.VOICE_STATE_UPDATE,
d: options,
});
}
@@ -191,7 +191,7 @@ class VoiceConnection extends EventEmitter {
return;
}
if (this.status === Constants.VoiceStatus.AUTHENTICATING) {
if (this.status === VoiceStatus.AUTHENTICATING) {
this.authentication.token = token;
this.authentication.endpoint = endpoint;
this.checkAuthenticated();
@@ -211,7 +211,7 @@ class VoiceConnection extends EventEmitter {
return;
}
if (this.status === Constants.VoiceStatus.AUTHENTICATING) {
if (this.status === VoiceStatus.AUTHENTICATING) {
this.authentication.sessionID = sessionID;
this.checkAuthenticated();
} else if (sessionID !== this.authentication.sessionID) {
@@ -234,7 +234,7 @@ class VoiceConnection extends EventEmitter {
if (token && endpoint && sessionID) {
clearTimeout(this.connectTimeout);
this.status = Constants.VoiceStatus.CONNECTING;
this.status = VoiceStatus.CONNECTING;
/**
* Emitted when we successfully initiate a voice connection.
* @event VoiceConnection#authenticated
@@ -251,7 +251,7 @@ class VoiceConnection extends EventEmitter {
*/
authenticateFailed(reason) {
clearTimeout(this.connectTimeout);
if (this.status === Constants.VoiceStatus.AUTHENTICATING) {
if (this.status === VoiceStatus.AUTHENTICATING) {
/**
* Emitted when we fail to initiate a voice connection.
* @event VoiceConnection#failed
@@ -261,7 +261,7 @@ class VoiceConnection extends EventEmitter {
} else {
this.emit('error', new Error(reason));
}
this.status = Constants.VoiceStatus.DISCONNECTED;
this.status = VoiceStatus.DISCONNECTED;
}
/**
@@ -294,7 +294,7 @@ class VoiceConnection extends EventEmitter {
this.authentication.token = token;
this.authentication.endpoint = endpoint;
this.status = Constants.VoiceStatus.RECONNECTING;
this.status = VoiceStatus.RECONNECTING;
/**
* Emitted when the voice connection is reconnecting (typically after a region change).
* @event VoiceConnection#reconnecting
@@ -320,7 +320,7 @@ class VoiceConnection extends EventEmitter {
*/
_disconnect() {
this.cleanup();
this.status = Constants.VoiceStatus.DISCONNECTED;
this.status = VoiceStatus.DISCONNECTED;
/**
* Emitted when the voice connection disconnects.
* @event VoiceConnection#disconnect
@@ -356,7 +356,7 @@ class VoiceConnection extends EventEmitter {
* @private
*/
connect() {
if (this.status !== Constants.VoiceStatus.RECONNECTING) {
if (this.status !== VoiceStatus.RECONNECTING) {
if (this.sockets.ws) throw new Error('WS_CONNECTION_EXISTS');
if (this.sockets.udp) throw new Error('UDP_CONNECTION_EXISTS');
}
@@ -407,7 +407,7 @@ class VoiceConnection extends EventEmitter {
this.authentication.encryptionMode = mode;
this.authentication.secretKey = secret;
this.status = Constants.VoiceStatus.CONNECTED;
this.status = VoiceStatus.CONNECTED;
/**
* Emitted once the connection is ready, when a promise to join a voice channel resolves,
* the connection will already be ready.
@@ -436,7 +436,7 @@ class VoiceConnection extends EventEmitter {
* @param {User} user The user that has started/stopped speaking
* @param {boolean} speaking Whether or not the user is speaking
*/
if (this.status === Constants.VoiceStatus.CONNECTED) this.emit('speaking', user, speaking);
if (this.status === VoiceStatus.CONNECTED) this.emit('speaking', user, speaking);
guild._memberSpeakUpdate(user_id, speaking);
}

View File

@@ -1,6 +1,6 @@
const udp = require('dgram');
const dns = require('dns');
const Constants = require('../../util/Constants');
const { VoiceOPCodes } = require('../../util/Constants');
const EventEmitter = require('events');
const { Error } = require('../../errors');
@@ -113,7 +113,7 @@ class VoiceConnectionUDPClient extends EventEmitter {
this.localPort = packet.port;
this.voiceConnection.sockets.ws.sendPacket({
op: Constants.VoiceOPCodes.SELECT_PROTOCOL,
op: VoiceOPCodes.SELECT_PROTOCOL,
d: {
protocol: 'udp',
data: {

View File

@@ -1,4 +1,4 @@
const Constants = require('../../util/Constants');
const { OPCodes, VoiceOPCodes } = require('../../util/Constants');
const SecretKey = require('./util/SecretKey');
const EventEmitter = require('events');
const { Error } = require('../../errors');
@@ -109,7 +109,7 @@ class VoiceWebSocket extends EventEmitter {
*/
onOpen() {
this.sendPacket({
op: Constants.OPCodes.DISPATCH,
op: OPCodes.DISPATCH,
d: {
server_id: this.voiceConnection.channel.guild.id,
user_id: this.client.user.id,
@@ -155,7 +155,7 @@ class VoiceWebSocket extends EventEmitter {
*/
onPacket(packet) {
switch (packet.op) {
case Constants.VoiceOPCodes.READY:
case VoiceOPCodes.READY:
this.setHeartbeat(packet.d.heartbeat_interval);
/**
* Emitted once the voice WebSocket receives the ready packet.
@@ -164,7 +164,7 @@ class VoiceWebSocket extends EventEmitter {
*/
this.emit('ready', packet.d);
break;
case Constants.VoiceOPCodes.SESSION_DESCRIPTION:
case VoiceOPCodes.SESSION_DESCRIPTION:
/**
* Emitted once the Voice Websocket receives a description of this voice session.
* @param {string} encryptionMode The type of encryption being used
@@ -173,7 +173,7 @@ class VoiceWebSocket extends EventEmitter {
*/
this.emit('sessionDescription', packet.d.mode, new SecretKey(packet.d.secret_key));
break;
case Constants.VoiceOPCodes.SPEAKING:
case VoiceOPCodes.SPEAKING:
/**
* Emitted whenever a speaking packet is received.
* @param {Object} data
@@ -229,7 +229,7 @@ class VoiceWebSocket extends EventEmitter {
* Sends a heartbeat packet.
*/
sendHeartbeat() {
this.sendPacket({ op: Constants.VoiceOPCodes.HEARTBEAT, d: null }).catch(() => {
this.sendPacket({ op: VoiceOPCodes.HEARTBEAT, d: null }).catch(() => {
this.emit('warn', 'Tried to send heartbeat, but connection is not open');
this.clearHeartbeat();
});

View File

@@ -1,6 +1,6 @@
const VolumeInterface = require('../util/VolumeInterface');
const VoiceBroadcast = require('../VoiceBroadcast');
const Constants = require('../../../util/Constants');
const { VoiceStatus } = require('../../../util/Constants');
const secretbox = require('../util/Secretbox');
@@ -109,7 +109,7 @@ class StreamDispatcher extends VolumeInterface {
setSpeaking(value) {
if (this.speaking === value) return;
if (this.player.voiceConnection.status !== Constants.VoiceStatus.CONNECTED) return;
if (this.player.voiceConnection.status !== VoiceStatus.CONNECTED) return;
this.speaking = value;
/**
* Emitted when the dispatcher starts/stops speaking.

View File

@@ -1,5 +1,5 @@
const EventEmitter = require('events');
const Constants = require('../../util/Constants');
const { DefaultOptions, Events, OPCodes, Status, WSCodes } = require('../../util/Constants');
const PacketManager = require('./packets/WebSocketPacketManager');
const WebSocket = require('../../WebSocket');
@@ -42,7 +42,7 @@ class WebSocketConnection extends EventEmitter {
* The current status of the client
* @type {number}
*/
this.status = Constants.Status.IDLE;
this.status = Status.IDLE;
/**
* The Packet Manager of the connection
@@ -93,7 +93,7 @@ class WebSocketConnection extends EventEmitter {
* @returns {void}
*/
triggerReady() {
if (this.status === Constants.Status.READY) {
if (this.status === Status.READY) {
this.debug('Tried to mark self as ready, but already ready');
return;
}
@@ -101,8 +101,8 @@ class WebSocketConnection extends EventEmitter {
* Emitted when the client becomes ready to start working.
* @event Client#ready
*/
this.status = Constants.Status.READY;
this.client.emit(Constants.Events.READY);
this.status = Status.READY;
this.client.emit(Events.READY);
this.packetManager.handleQueue();
}
@@ -111,13 +111,13 @@ class WebSocketConnection extends EventEmitter {
* @returns {void}
*/
checkIfReady() {
if (this.status === Constants.Status.READY || this.status === Constants.Status.NEARLY) return false;
if (this.status === Status.READY || this.status === Status.NEARLY) return false;
let unavailableGuilds = 0;
for (const guild of this.client.guilds.values()) {
if (!guild.available) unavailableGuilds++;
}
if (unavailableGuilds === 0) {
this.status = Constants.Status.NEARLY;
this.status = Status.NEARLY;
if (!this.client.options.fetchAllMembers) return this.triggerReady();
// Fetch all members before marking self as ready
const promises = this.client.guilds.map(g => g.members.fetch());
@@ -208,12 +208,12 @@ class WebSocketConnection extends EventEmitter {
this.expectingClose = false;
this.gateway = gateway;
this.debug(`Connecting to ${gateway}`);
const ws = this.ws = WebSocket.create(gateway, { v: Constants.DefaultOptions.ws.version });
const ws = this.ws = WebSocket.create(gateway, { v: DefaultOptions.ws.version });
ws.onmessage = this.onMessage.bind(this);
ws.onopen = this.onOpen.bind(this);
ws.onerror = this.onError.bind(this);
ws.onclose = this.onClose.bind(this);
this.status = Constants.Status.CONNECTING;
this.status = Status.CONNECTING;
return true;
}
@@ -232,7 +232,7 @@ class WebSocketConnection extends EventEmitter {
ws.close(1000);
this.packetManager.handleQueue();
this.ws = null;
this.status = Constants.Status.DISCONNECTED;
this.status = Status.DISCONNECTED;
this.ratelimit.remaining = this.ratelimit.total;
return true;
}
@@ -273,18 +273,18 @@ class WebSocketConnection extends EventEmitter {
return false;
}
switch (packet.op) {
case Constants.OPCodes.HELLO:
case OPCodes.HELLO:
return this.heartbeat(packet.d.heartbeat_interval);
case Constants.OPCodes.RECONNECT:
case OPCodes.RECONNECT:
return this.reconnect();
case Constants.OPCodes.INVALID_SESSION:
case OPCodes.INVALID_SESSION:
if (!packet.d) this.sessionID = null;
this.sequence = -1;
this.debug('Session invalidated -- will identify with a new session');
return this.identify(packet.d ? 2500 : 0);
case Constants.OPCodes.HEARTBEAT_ACK:
case OPCodes.HEARTBEAT_ACK:
return this.ackHeartbeat();
case Constants.OPCodes.HEARTBEAT:
case OPCodes.HEARTBEAT:
return this.heartbeat();
default:
return this.packetManager.handle(packet);
@@ -310,7 +310,7 @@ class WebSocketConnection extends EventEmitter {
* Emitted whenever the client tries to reconnect to the WebSocket.
* @event Client#reconnecting
*/
this.client.emit(Constants.Events.RECONNECTING);
this.client.emit(Events.RECONNECTING);
this.connect(this.gateway, 5500, true);
}
@@ -328,7 +328,7 @@ class WebSocketConnection extends EventEmitter {
* @event Client#error
* @param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
this.client.emit(Events.ERROR, error);
}
/**
@@ -347,15 +347,15 @@ class WebSocketConnection extends EventEmitter {
this.emit('close', event);
this.heartbeat(-1);
// Should we reconnect?
if (event.code === 1000 ? this.expectingClose : Constants.WSCodes[event.code]) {
if (event.code === 1000 ? this.expectingClose : WSCodes[event.code]) {
this.expectingClose = false;
/**
* Emitted when the client's WebSocket disconnects and will no longer attempt to reconnect.
* @event Client#disconnect
* @param {CloseEvent} event The WebSocket close event
*/
this.client.emit(Constants.Events.DISCONNECT, event);
this.debug(Constants.WSCodes[event.code]);
this.client.emit(Events.DISCONNECT, event);
this.debug(WSCodes[event.code]);
this.destroy();
return;
}
@@ -392,7 +392,7 @@ class WebSocketConnection extends EventEmitter {
this.debug('Sending a heartbeat');
this.lastPingTimestamp = Date.now();
this.send({
op: Constants.OPCodes.HEARTBEAT,
op: OPCodes.HEARTBEAT,
d: this.sequence,
});
}
@@ -426,7 +426,7 @@ class WebSocketConnection extends EventEmitter {
// Send the payload
this.debug('Identifying as a new session');
this.send({ op: Constants.OPCodes.IDENTIFY, d });
this.send({ op: OPCodes.IDENTIFY, d });
}
/**
@@ -447,7 +447,7 @@ class WebSocketConnection extends EventEmitter {
};
return this.send({
op: Constants.OPCodes.RESUME,
op: OPCodes.RESUME,
d,
});
}

View File

@@ -1,5 +1,5 @@
const EventEmitter = require('events');
const Constants = require('../../util/Constants');
const { Events, Status } = require('../../util/Constants');
const WebSocketConnection = require('./WebSocketConnection');
/**
@@ -37,7 +37,7 @@ class WebSocketManager extends EventEmitter {
* @returns {void}
*/
debug(message) {
return this.client.emit(Constants.Events.DEBUG, `[ws] ${message}`);
return this.client.emit(Events.DEBUG, `[ws] ${message}`);
}
/**
@@ -76,8 +76,8 @@ class WebSocketManager extends EventEmitter {
return true;
}
switch (this.connection.status) {
case Constants.Status.IDLE:
case Constants.Status.DISCONNECTED:
case Status.IDLE:
case Status.DISCONNECTED:
this.connection.connect(gateway, 5500);
return true;
default:

View File

@@ -1,13 +1,13 @@
const Constants = require('../../../util/Constants');
const { OPCodes, Status, WSEvents } = require('../../../util/Constants');
const BeforeReadyWhitelist = [
Constants.WSEvents.READY,
Constants.WSEvents.RESUMED,
Constants.WSEvents.GUILD_CREATE,
Constants.WSEvents.GUILD_DELETE,
Constants.WSEvents.GUILD_MEMBERS_CHUNK,
Constants.WSEvents.GUILD_MEMBER_ADD,
Constants.WSEvents.GUILD_MEMBER_REMOVE,
WSEvents.READY,
WSEvents.RESUMED,
WSEvents.GUILD_CREATE,
WSEvents.GUILD_DELETE,
WSEvents.GUILD_MEMBERS_CHUNK,
WSEvents.GUILD_MEMBER_ADD,
WSEvents.GUILD_MEMBER_REMOVE,
];
class WebSocketPacketManager {
@@ -16,43 +16,43 @@ class WebSocketPacketManager {
this.handlers = {};
this.queue = [];
this.register(Constants.WSEvents.READY, require('./handlers/Ready'));
this.register(Constants.WSEvents.RESUMED, require('./handlers/Resumed'));
this.register(Constants.WSEvents.GUILD_CREATE, require('./handlers/GuildCreate'));
this.register(Constants.WSEvents.GUILD_DELETE, require('./handlers/GuildDelete'));
this.register(Constants.WSEvents.GUILD_UPDATE, require('./handlers/GuildUpdate'));
this.register(Constants.WSEvents.GUILD_BAN_ADD, require('./handlers/GuildBanAdd'));
this.register(Constants.WSEvents.GUILD_BAN_REMOVE, require('./handlers/GuildBanRemove'));
this.register(Constants.WSEvents.GUILD_MEMBER_ADD, require('./handlers/GuildMemberAdd'));
this.register(Constants.WSEvents.GUILD_MEMBER_REMOVE, require('./handlers/GuildMemberRemove'));
this.register(Constants.WSEvents.GUILD_MEMBER_UPDATE, require('./handlers/GuildMemberUpdate'));
this.register(Constants.WSEvents.GUILD_ROLE_CREATE, require('./handlers/GuildRoleCreate'));
this.register(Constants.WSEvents.GUILD_ROLE_DELETE, require('./handlers/GuildRoleDelete'));
this.register(Constants.WSEvents.GUILD_ROLE_UPDATE, require('./handlers/GuildRoleUpdate'));
this.register(Constants.WSEvents.GUILD_EMOJIS_UPDATE, require('./handlers/GuildEmojisUpdate'));
this.register(Constants.WSEvents.GUILD_MEMBERS_CHUNK, require('./handlers/GuildMembersChunk'));
this.register(Constants.WSEvents.CHANNEL_CREATE, require('./handlers/ChannelCreate'));
this.register(Constants.WSEvents.CHANNEL_DELETE, require('./handlers/ChannelDelete'));
this.register(Constants.WSEvents.CHANNEL_UPDATE, require('./handlers/ChannelUpdate'));
this.register(Constants.WSEvents.CHANNEL_PINS_UPDATE, require('./handlers/ChannelPinsUpdate'));
this.register(Constants.WSEvents.PRESENCE_UPDATE, require('./handlers/PresenceUpdate'));
this.register(Constants.WSEvents.USER_UPDATE, require('./handlers/UserUpdate'));
this.register(Constants.WSEvents.USER_NOTE_UPDATE, require('./handlers/UserNoteUpdate'));
this.register(Constants.WSEvents.USER_SETTINGS_UPDATE, require('./handlers/UserSettingsUpdate'));
this.register(Constants.WSEvents.USER_GUILD_SETTINGS_UPDATE, require('./handlers/UserGuildSettingsUpdate'));
this.register(Constants.WSEvents.VOICE_STATE_UPDATE, require('./handlers/VoiceStateUpdate'));
this.register(Constants.WSEvents.TYPING_START, require('./handlers/TypingStart'));
this.register(Constants.WSEvents.MESSAGE_CREATE, require('./handlers/MessageCreate'));
this.register(Constants.WSEvents.MESSAGE_DELETE, require('./handlers/MessageDelete'));
this.register(Constants.WSEvents.MESSAGE_UPDATE, require('./handlers/MessageUpdate'));
this.register(Constants.WSEvents.MESSAGE_DELETE_BULK, require('./handlers/MessageDeleteBulk'));
this.register(Constants.WSEvents.VOICE_SERVER_UPDATE, require('./handlers/VoiceServerUpdate'));
this.register(Constants.WSEvents.GUILD_SYNC, require('./handlers/GuildSync'));
this.register(Constants.WSEvents.RELATIONSHIP_ADD, require('./handlers/RelationshipAdd'));
this.register(Constants.WSEvents.RELATIONSHIP_REMOVE, require('./handlers/RelationshipRemove'));
this.register(Constants.WSEvents.MESSAGE_REACTION_ADD, require('./handlers/MessageReactionAdd'));
this.register(Constants.WSEvents.MESSAGE_REACTION_REMOVE, require('./handlers/MessageReactionRemove'));
this.register(Constants.WSEvents.MESSAGE_REACTION_REMOVE_ALL, require('./handlers/MessageReactionRemoveAll'));
this.register(WSEvents.READY, require('./handlers/Ready'));
this.register(WSEvents.RESUMED, require('./handlers/Resumed'));
this.register(WSEvents.GUILD_CREATE, require('./handlers/GuildCreate'));
this.register(WSEvents.GUILD_DELETE, require('./handlers/GuildDelete'));
this.register(WSEvents.GUILD_UPDATE, require('./handlers/GuildUpdate'));
this.register(WSEvents.GUILD_BAN_ADD, require('./handlers/GuildBanAdd'));
this.register(WSEvents.GUILD_BAN_REMOVE, require('./handlers/GuildBanRemove'));
this.register(WSEvents.GUILD_MEMBER_ADD, require('./handlers/GuildMemberAdd'));
this.register(WSEvents.GUILD_MEMBER_REMOVE, require('./handlers/GuildMemberRemove'));
this.register(WSEvents.GUILD_MEMBER_UPDATE, require('./handlers/GuildMemberUpdate'));
this.register(WSEvents.GUILD_ROLE_CREATE, require('./handlers/GuildRoleCreate'));
this.register(WSEvents.GUILD_ROLE_DELETE, require('./handlers/GuildRoleDelete'));
this.register(WSEvents.GUILD_ROLE_UPDATE, require('./handlers/GuildRoleUpdate'));
this.register(WSEvents.GUILD_EMOJIS_UPDATE, require('./handlers/GuildEmojisUpdate'));
this.register(WSEvents.GUILD_MEMBERS_CHUNK, require('./handlers/GuildMembersChunk'));
this.register(WSEvents.CHANNEL_CREATE, require('./handlers/ChannelCreate'));
this.register(WSEvents.CHANNEL_DELETE, require('./handlers/ChannelDelete'));
this.register(WSEvents.CHANNEL_UPDATE, require('./handlers/ChannelUpdate'));
this.register(WSEvents.CHANNEL_PINS_UPDATE, require('./handlers/ChannelPinsUpdate'));
this.register(WSEvents.PRESENCE_UPDATE, require('./handlers/PresenceUpdate'));
this.register(WSEvents.USER_UPDATE, require('./handlers/UserUpdate'));
this.register(WSEvents.USER_NOTE_UPDATE, require('./handlers/UserNoteUpdate'));
this.register(WSEvents.USER_SETTINGS_UPDATE, require('./handlers/UserSettingsUpdate'));
this.register(WSEvents.USER_GUILD_SETTINGS_UPDATE, require('./handlers/UserGuildSettingsUpdate'));
this.register(WSEvents.VOICE_STATE_UPDATE, require('./handlers/VoiceStateUpdate'));
this.register(WSEvents.TYPING_START, require('./handlers/TypingStart'));
this.register(WSEvents.MESSAGE_CREATE, require('./handlers/MessageCreate'));
this.register(WSEvents.MESSAGE_DELETE, require('./handlers/MessageDelete'));
this.register(WSEvents.MESSAGE_UPDATE, require('./handlers/MessageUpdate'));
this.register(WSEvents.MESSAGE_DELETE_BULK, require('./handlers/MessageDeleteBulk'));
this.register(WSEvents.VOICE_SERVER_UPDATE, require('./handlers/VoiceServerUpdate'));
this.register(WSEvents.GUILD_SYNC, require('./handlers/GuildSync'));
this.register(WSEvents.RELATIONSHIP_ADD, require('./handlers/RelationshipAdd'));
this.register(WSEvents.RELATIONSHIP_REMOVE, require('./handlers/RelationshipRemove'));
this.register(WSEvents.MESSAGE_REACTION_ADD, require('./handlers/MessageReactionAdd'));
this.register(WSEvents.MESSAGE_REACTION_REMOVE, require('./handlers/MessageReactionRemove'));
this.register(WSEvents.MESSAGE_REACTION_REMOVE_ALL, require('./handlers/MessageReactionRemoveAll'));
}
get client() {
@@ -71,19 +71,19 @@ class WebSocketPacketManager {
}
handle(packet, queue = false) {
if (packet.op === Constants.OPCodes.HEARTBEAT_ACK) {
if (packet.op === OPCodes.HEARTBEAT_ACK) {
this.ws.client._pong(this.ws.client._pingTimestamp);
this.ws.lastHeartbeatAck = true;
this.ws.client.emit('debug', 'Heartbeat acknowledged');
} else if (packet.op === Constants.OPCodes.HEARTBEAT) {
} else if (packet.op === OPCodes.HEARTBEAT) {
this.client.ws.send({
op: Constants.OPCodes.HEARTBEAT,
op: OPCodes.HEARTBEAT,
d: this.client.ws.sequence,
});
this.ws.client.emit('debug', 'Received gateway heartbeat');
}
if (this.ws.status === Constants.Status.RECONNECTING) {
if (this.ws.status === Status.RECONNECTING) {
this.ws.reconnecting = false;
this.ws.checkIfReady();
}
@@ -92,7 +92,7 @@ class WebSocketPacketManager {
if (this.ws.disabledEvents[packet.t] !== undefined) return false;
if (this.ws.status !== Constants.Status.READY) {
if (this.ws.status !== Status.READY) {
if (BeforeReadyWhitelist.indexOf(packet.t) === -1) {
this.queue.push(packet);
return false;

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
/*
{ t: 'CHANNEL_PINS_UPDATE',
@@ -16,7 +16,7 @@ class ChannelPinsUpdate extends AbstractHandler {
const data = packet.d;
const channel = client.channels.get(data.channel_id);
const time = new Date(data.last_pin_timestamp);
if (channel && time) client.emit(Constants.Events.CHANNEL_PINS_UPDATE, channel, time);
if (channel && time) client.emit(Events.CHANNEL_PINS_UPDATE, channel, time);
}
}

View File

@@ -1,11 +1,11 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class ChannelUpdateHandler extends AbstractHandler {
handle(packet) {
const { old, updated } = this.packetManager.client.actions.ChannelUpdate.handle(packet.d);
if (old && updated) {
this.packetManager.client.emit(Constants.Events.CHANNEL_UPDATE, old, updated);
this.packetManager.client.emit(Events.CHANNEL_UPDATE, old, updated);
}
}
}

View File

@@ -1,7 +1,7 @@
// ##untested handler##
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class GuildBanAddHandler extends AbstractHandler {
handle(packet) {
@@ -9,7 +9,7 @@ class GuildBanAddHandler extends AbstractHandler {
const data = packet.d;
const guild = client.guilds.get(data.guild_id);
const user = client.users.get(data.user.id);
if (guild && user) client.emit(Constants.Events.GUILD_BAN_ADD, guild, user);
if (guild && user) client.emit(Events.GUILD_BAN_ADD, guild, user);
}
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events, Status } = require('../../../../util/Constants');
class GuildCreateHandler extends AbstractHandler {
async handle(packet) {
@@ -16,7 +16,7 @@ class GuildCreateHandler extends AbstractHandler {
} else {
// A new guild
guild = client.guilds.create(data);
const emitEvent = client.ws.connection.status === Constants.Status.READY;
const emitEvent = client.ws.connection.status === Status.READY;
if (emitEvent) {
/**
* Emitted whenever the client joins a guild.
@@ -24,7 +24,7 @@ class GuildCreateHandler extends AbstractHandler {
* @param {Guild} guild The created guild
*/
if (client.options.fetchAllMembers) await guild.members.fetch();
client.emit(Constants.Events.GUILD_CREATE, guild);
client.emit(Events.GUILD_CREATE, guild);
}
}
}

View File

@@ -1,7 +1,7 @@
// ##untested handler##
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events, Status } = require('../../../../util/Constants');
class GuildMemberAddHandler extends AbstractHandler {
handle(packet) {
@@ -11,8 +11,8 @@ class GuildMemberAddHandler extends AbstractHandler {
if (guild) {
guild.memberCount++;
const member = guild.members.create(data);
if (client.ws.connection.status === Constants.Status.READY) {
client.emit(Constants.Events.GUILD_MEMBER_ADD, member);
if (client.ws.connection.status === Status.READY) {
client.emit(Events.GUILD_MEMBER_ADD, member);
}
}
}

View File

@@ -1,7 +1,7 @@
// ##untested handler##
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events, Status } = require('../../../../util/Constants');
class GuildMemberUpdateHandler extends AbstractHandler {
handle(packet) {
@@ -12,14 +12,14 @@ class GuildMemberUpdateHandler extends AbstractHandler {
const member = guild.members.get(data.user.id);
if (member) {
const old = member._update(data);
if (client.ws.connection.status === Constants.Status.READY) {
if (client.ws.connection.status === Status.READY) {
/**
* Emitted whenever a guild member changes - i.e. new role, removed role, nickname.
* @event Client#guildMemberUpdate
* @param {GuildMember} oldMember The member before the update
* @param {GuildMember} newMember The member after the update
*/
client.emit(Constants.Events.GUILD_MEMBER_UPDATE, old, member);
client.emit(Events.GUILD_MEMBER_UPDATE, old, member);
}
}
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
const Collection = require('../../../../util/Collection');
class GuildMembersChunkHandler extends AbstractHandler {
@@ -12,7 +12,7 @@ class GuildMembersChunkHandler extends AbstractHandler {
for (const member of data.members) members.set(member.user.id, guild.members.create(member));
client.emit(Constants.Events.GUILD_MEMBERS_CHUNK, members, guild);
client.emit(Events.GUILD_MEMBERS_CHUNK, members, guild);
client.ws.lastHeartbeatAck = true;
}

View File

@@ -1,12 +1,12 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class MessageReactionAddHandler extends AbstractHandler {
handle(packet) {
const client = this.packetManager.client;
const data = packet.d;
const { user, reaction } = client.actions.MessageReactionAdd.handle(data);
if (reaction) client.emit(Constants.Events.MESSAGE_REACTION_ADD, reaction, user);
if (reaction) client.emit(Events.MESSAGE_REACTION_ADD, reaction, user);
}
}

View File

@@ -1,11 +1,11 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class MessageUpdateHandler extends AbstractHandler {
handle(packet) {
const { old, updated } = this.packetManager.client.actions.MessageUpdate.handle(packet.d);
if (old && updated) {
this.packetManager.client.emit(Constants.Events.MESSAGE_UPDATE, old, updated);
this.packetManager.client.emit(Events.MESSAGE_UPDATE, old, updated);
}
}
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class PresenceUpdateHandler extends AbstractHandler {
handle(packet) {
@@ -19,7 +19,7 @@ class PresenceUpdateHandler extends AbstractHandler {
const oldUser = user._update(data.user);
if (!user.equals(oldUser)) {
client.emit(Constants.Events.USER_UPDATE, oldUser, user);
client.emit(Events.USER_UPDATE, oldUser, user);
}
if (guild) {
@@ -31,10 +31,10 @@ class PresenceUpdateHandler extends AbstractHandler {
deaf: false,
mute: false,
});
client.emit(Constants.Events.GUILD_MEMBER_AVAILABLE, member);
client.emit(Events.GUILD_MEMBER_AVAILABLE, member);
}
if (member) {
if (client.listenerCount(Constants.Events.PRESENCE_UPDATE) === 0) {
if (client.listenerCount(Events.PRESENCE_UPDATE) === 0) {
guild.presences.create(data);
return;
}
@@ -43,7 +43,7 @@ class PresenceUpdateHandler extends AbstractHandler {
oldMember.frozenPresence = member.presence._clone();
}
guild.presences.create(data);
client.emit(Constants.Events.PRESENCE_UPDATE, oldMember, member);
client.emit(Events.PRESENCE_UPDATE, oldMember, member);
} else {
guild.presences.create(data);
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
const ClientUser = require('../../../../structures/ClientUser');
class ReadyHandler extends AbstractHandler {
@@ -69,7 +69,7 @@ class ReadyHandler extends AbstractHandler {
ws.sessionID = data.session_id;
ws._trace = data._trace;
client.emit(Constants.Events.DEBUG, `READY ${ws._trace.join(' -> ')} ${ws.sessionID}`);
client.emit(Events.DEBUG, `READY ${ws._trace.join(' -> ')} ${ws.sessionID}`);
ws.checkIfReady();
}
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events, Status } = require('../../../../util/Constants');
class ResumedHandler extends AbstractHandler {
handle(packet) {
@@ -8,13 +8,13 @@ class ResumedHandler extends AbstractHandler {
ws._trace = packet.d._trace;
ws.status = Constants.Status.READY;
ws.status = Status.READY;
this.packetManager.handleQueue();
const replayed = ws.sequence - ws.closeSequence;
ws.debug(`RESUMED ${ws._trace.join(' -> ')} | replayed ${replayed} events.`);
client.emit(Constants.Events.RESUMED, replayed);
client.emit(Events.RESUMED, replayed);
ws.heartbeat();
}
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class TypingStartHandler extends AbstractHandler {
handle(packet) {
@@ -11,7 +11,7 @@ class TypingStartHandler extends AbstractHandler {
if (channel && user) {
if (channel.type === 'voice') {
client.emit(Constants.Events.WARN, `Discord sent a typing packet to voice channel ${channel.id}`);
client.emit(Events.WARN, `Discord sent a typing packet to voice channel ${channel.id}`);
return;
}
if (channel._typing.has(user.id)) {
@@ -20,7 +20,7 @@ class TypingStartHandler extends AbstractHandler {
typing.resetTimeout(tooLate(channel, user));
} else {
channel._typing.set(user.id, new TypingData(client, timestamp, timestamp, tooLate(channel, user)));
client.emit(Constants.Events.TYPING_START, channel, user);
client.emit(Events.TYPING_START, channel, user);
}
}
}
@@ -46,7 +46,7 @@ class TypingData {
function tooLate(channel, user) {
return channel.client.setTimeout(() => {
channel.client.emit(Constants.Events.TYPING_STOP, channel, user, channel._typing.get(user.id));
channel.client.emit(Events.TYPING_STOP, channel, user, channel._typing.get(user.id));
channel._typing.delete(user.id);
}, 6000);
}

View File

@@ -1,5 +1,5 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
const ClientUserGuildSettings = require('../../../../structures/ClientUserGuildSettings');
class UserGuildSettingsUpdateHandler extends AbstractHandler {
@@ -8,7 +8,7 @@ class UserGuildSettingsUpdateHandler extends AbstractHandler {
const settings = client.user.guildSettings.get(packet.d.guild_id);
if (settings) settings.patch(packet.d);
else client.user.guildSettings.set(packet.d.guild_id, new ClientUserGuildSettings(this.client, packet.d));
client.emit(Constants.Events.USER_GUILD_SETTINGS_UPDATE, client.user.guildSettings.get(packet.d.guild_id));
client.emit(Events.USER_GUILD_SETTINGS_UPDATE, client.user.guildSettings.get(packet.d.guild_id));
}
}

View File

@@ -1,11 +1,11 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class UserSettingsUpdateHandler extends AbstractHandler {
handle(packet) {
const client = this.packetManager.client;
client.user.settings.patch(packet.d);
client.emit(Constants.Events.USER_SETTINGS_UPDATE, client.user.settings);
client.emit(Events.USER_SETTINGS_UPDATE, client.user.settings);
}
}

View File

@@ -1,6 +1,6 @@
const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');
const { Events } = require('../../../../util/Constants');
class VoiceStateUpdateHandler extends AbstractHandler {
handle(packet) {
@@ -20,7 +20,7 @@ class VoiceStateUpdateHandler extends AbstractHandler {
guild.voiceStates.set(member.user.id, data);
client.emit(Constants.Events.VOICE_STATE_UPDATE, oldMember, member);
client.emit(Events.VOICE_STATE_UPDATE, oldMember, member);
}
}
}

View File

@@ -3,7 +3,7 @@ const handlers = require('./handlers');
const APIRequest = require('./APIRequest');
const routeBuilder = require('./APIRouter');
const { Error } = require('../errors');
const Constants = require('../util/Constants');
const { Endpoints } = require('../util/Constants');
class RESTManager {
constructor(client, tokenPrefix = 'Bot') {
@@ -29,7 +29,7 @@ class RESTManager {
}
get cdn() {
return Constants.Endpoints.CDN(this.client.options.http.cdn);
return Endpoints.CDN(this.client.options.http.cdn);
}
destroy() {

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { Package } = require('../util/Constants');
class UserAgentManager {
constructor() {
@@ -18,8 +18,8 @@ class UserAgentManager {
}
UserAgentManager.DEFAULT = {
url: Constants.Package.homepage.split('#')[0],
version: Constants.Package.version,
url: Package.homepage.split('#')[0],
version: Package.version,
};
module.exports = UserAgentManager;

View File

@@ -1,5 +1,5 @@
const Util = require('../util/Util');
const Constants = require('../util/Constants');
const { Events } = require('../util/Constants');
const { Error } = require('../errors');
/**
@@ -124,7 +124,7 @@ class ShardClientUtil {
_respond(type, message) {
this.send(message).catch(err => {
err.message = `Error when sending ${type} response to master process: ${err.message}`;
this.client.emit(Constants.Events.ERROR, err);
this.client.emit(Events.ERROR, err);
});
}
@@ -137,7 +137,7 @@ class ShardClientUtil {
if (!this._singleton) {
this._singleton = new this(client);
} else {
client.emit(Constants.Events.WARN,
client.emit(Events.WARN,
'Multiple clients created in child process; only the first will handle sharding helpers.');
}
return this._singleton;

View File

@@ -1,6 +1,6 @@
const DataStore = require('./DataStore');
const Channel = require('../structures/Channel');
const Constants = require('../util/Constants');
const { Events } = require('../util/Constants');
const kLru = Symbol('LRU');
const lruable = ['group', 'dm'];
@@ -58,7 +58,7 @@ class ChannelStore extends DataStore {
const channel = Channel.create(this.client, data, guild);
if (!channel) {
this.client.emit(Constants.Events.DEBUG, `Failed to find guild for channel ${data.id} ${data.type}`);
this.client.emit(Events.DEBUG, `Failed to find guild for channel ${data.id} ${data.type}`);
return null;
}

View File

@@ -1,6 +1,6 @@
const PresenceStore = require('./PresenceStore');
const Collection = require('../util/Collection');
const Constants = require('../util/Constants');
const { ActivityTypes, OPCodes } = require('../util/Constants');
const { Presence } = require('../structures/Presence');
const { TypeError } = require('../errors');
@@ -34,7 +34,7 @@ class ClientPresenceStore extends PresenceStore {
since: since != null ? since : null, // eslint-disable-line eqeqeq
status: status || this.clientPresence.status,
game: activity ? {
type: typeof activity.type === 'number' ? activity.type : Constants.ActivityTypes.indexOf(activity.type),
type: typeof activity.type === 'number' ? activity.type : ActivityTypes.indexOf(activity.type),
name: activity.name,
url: activity.url,
details: activity.details || undefined,
@@ -54,7 +54,7 @@ class ClientPresenceStore extends PresenceStore {
};
this.clientPresence.patch(packet);
this.client.ws.send({ op: Constants.OPCodes.STATUS_UPDATE, d: packet });
this.client.ws.send({ op: OPCodes.STATUS_UPDATE, d: packet });
return this.clientPresence;
}
}

View File

@@ -1,6 +1,6 @@
const DataStore = require('./DataStore');
const GuildMember = require('../structures/GuildMember');
const Constants = require('../util/Constants');
const { Events, OPCodes } = require('../util/Constants');
const Collection = require('../util/Collection');
const { Error } = require('../errors');
@@ -112,7 +112,7 @@ class GuildMemberStore extends DataStore {
return;
}
this.guild.client.ws.send({
op: Constants.OPCodes.REQUEST_GUILD_MEMBERS,
op: OPCodes.REQUEST_GUILD_MEMBERS,
d: {
guild_id: this.guild.id,
query,
@@ -128,13 +128,13 @@ class GuildMemberStore extends DataStore {
if (this.guild.memberCount <= this.size ||
((query || limit) && members.size < 1000) ||
(limit && fetchedMembers.size >= limit)) {
this.guild.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
this.guild.client.removeListener(Events.GUILD_MEMBERS_CHUNK, handler);
resolve(query || limit ? fetchedMembers : this);
}
};
this.guild.client.on(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
this.guild.client.on(Events.GUILD_MEMBERS_CHUNK, handler);
this.guild.client.setTimeout(() => {
this.guild.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
this.guild.client.removeListener(Events.GUILD_MEMBERS_CHUNK, handler);
reject(new Error('GUILD_MEMBERS_TIMEOUT'));
}, 120e3);
});

View File

@@ -1,6 +1,6 @@
const Snowflake = require('../util/Snowflake');
const Base = require('./Base');
const Constants = require('../util/Constants');
const { ChannelTypes } = require('../util/Constants');
/**
* Represents any channel on Discord.
@@ -10,7 +10,7 @@ class Channel extends Base {
constructor(client, data) {
super(client);
const type = Object.keys(Constants.ChannelTypes)[data.type];
const type = Object.keys(ChannelTypes)[data.type];
/**
* The type of the channel, either:
* * `dm` - a DM channel
@@ -72,23 +72,22 @@ class Channel extends Base {
const VoiceChannel = require('./VoiceChannel');
const CategoryChannel = require('./CategoryChannel');
const GuildChannel = require('./GuildChannel');
const types = Constants.ChannelTypes;
let channel;
if (data.type === types.DM) {
if (data.type === ChannelTypes.DM) {
channel = new DMChannel(client, data);
} else if (data.type === types.GROUP) {
} else if (data.type === ChannelTypes.GROUP) {
channel = new GroupDMChannel(client, data);
} else {
guild = guild || client.guilds.get(data.guild_id);
if (guild) {
switch (data.type) {
case types.TEXT:
case ChannelTypes.TEXT:
channel = new TextChannel(guild, data);
break;
case types.VOICE:
case ChannelTypes.VOICE:
channel = new VoiceChannel(guild, data);
break;
case types.CATEGORY:
case ChannelTypes.CATEGORY:
channel = new CategoryChannel(guild, data);
break;
default:

View File

@@ -1,5 +1,5 @@
const Snowflake = require('../util/Snowflake');
const Constants = require('../util/Constants');
const { ClientApplicationAssetTypes, Endpoints } = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const Base = require('./Base');
@@ -140,7 +140,7 @@ class ClientApplication extends Base {
*/
coverImage({ format, size } = {}) {
if (!this.cover) return null;
return Constants.Endpoints
return Endpoints
.CDN(this.client.options.http.cdn)
.AppIcon(this.id, this.cover, { format, size });
}
@@ -154,7 +154,7 @@ class ClientApplication extends Base {
.then(assets => assets.map(a => ({
id: a.id,
name: a.name,
type: Object.keys(Constants.ClientApplicationAssetTypes)[a.type - 1],
type: Object.keys(ClientApplicationAssetTypes)[a.type - 1],
})));
}
@@ -170,7 +170,7 @@ class ClientApplication extends Base {
this.client.api.applications(this.id).assets.post({ data: {
name,
data: b64,
type: Constants.ClientApplicationAssetTypes[type.toUpperCase()],
type: ClientApplicationAssetTypes[type.toUpperCase()],
} }));
}

View File

@@ -2,7 +2,7 @@ const User = require('./User');
const Collection = require('../util/Collection');
const ClientUserSettings = require('./ClientUserSettings');
const ClientUserGuildSettings = require('./ClientUserGuildSettings');
const Constants = require('../util/Constants');
const { Events } = require('../util/Constants');
const Util = require('../util/Util');
const DataResolver = require('../util/DataResolver');
const Guild = require('./Guild');
@@ -278,15 +278,15 @@ class ClientUser extends User {
const handleGuild = guild => {
if (guild.id === data.id) {
this.client.removeListener(Constants.Events.GUILD_CREATE, handleGuild);
this.client.removeListener(Events.GUILD_CREATE, handleGuild);
this.client.clearTimeout(timeout);
resolve(guild);
}
};
this.client.on(Constants.Events.GUILD_CREATE, handleGuild);
this.client.on(Events.GUILD_CREATE, handleGuild);
const timeout = this.client.setTimeout(() => {
this.client.removeListener(Constants.Events.GUILD_CREATE, handleGuild);
this.client.removeListener(Events.GUILD_CREATE, handleGuild);
resolve(this.client.guilds.create(data));
}, 10000);
return undefined;

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { UserChannelOverrideMap } = require('../util/Constants');
/**
* A wrapper around the ClientUser's channel overrides.
@@ -14,7 +14,7 @@ class ClientUserChannelOverride {
* @private
*/
patch(data) {
for (const [key, value] of Object.entries(Constants.UserChannelOverrideMap)) {
for (const [key, value] of Object.entries(UserChannelOverrideMap)) {
if (!data.hasOwnProperty(key)) continue;
if (typeof value === 'function') {
this[value.name] = value(data[key]);

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { UserGuildSettingsMap } = require('../util/Constants');
const Collection = require('../util/Collection');
const ClientUserChannelOverride = require('./ClientUserChannelOverride');
@@ -29,7 +29,7 @@ class ClientUserGuildSettings {
* @private
*/
patch(data) {
for (const [key, value] of Object.entries(Constants.UserGuildSettingsMap)) {
for (const [key, value] of Object.entries(UserGuildSettingsMap)) {
if (!data.hasOwnProperty(key)) continue;
if (key === 'channel_overrides') {
for (const channel of data[key]) {

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { UserSettingsMap } = require('../util/Constants');
const Util = require('../util/Util');
const { Error } = require('../errors');
@@ -17,7 +17,7 @@ class ClientUserSettings {
* @private
*/
patch(data) {
for (const [key, value] of Object.entries(Constants.UserSettingsMap)) {
for (const [key, value] of Object.entries(UserSettingsMap)) {
if (!data.hasOwnProperty(key)) continue;
if (typeof value === 'function') {
this[value.name] = value(data[key]);

View File

@@ -3,7 +3,7 @@ const GuildAuditLogs = require('./GuildAuditLogs');
const Webhook = require('./Webhook');
const GuildMember = require('./GuildMember');
const VoiceRegion = require('./VoiceRegion');
const Constants = require('../util/Constants');
const { ChannelTypes, Events } = require('../util/Constants');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
const DataResolver = require('../util/DataResolver');
@@ -923,7 +923,7 @@ class Guild extends Base {
return this.client.api.guilds(this.id).channels.post({
data: {
name,
type: Constants.ChannelTypes[type.toUpperCase()],
type: ChannelTypes[type.toUpperCase()],
permission_overwrites: overwrites,
},
reason,
@@ -1128,7 +1128,7 @@ class Guild extends Base {
* @param {GuildMember} member The member that started/stopped speaking
* @param {boolean} speaking Whether or not the member is speaking
*/
this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking);
this.client.emit(Events.GUILD_MEMBER_SPEAKING, member, speaking);
}
}
@@ -1137,7 +1137,7 @@ class Guild extends Base {
}
_sortedChannels(channel) {
const category = channel.type === Constants.ChannelTypes.CATEGORY;
const category = channel.type === ChannelTypes.CATEGORY;
return Util.discordSort(this.channels.filter(c =>
c.type === channel.type && (category || c.parent === channel.parent)));
}

View File

@@ -5,7 +5,7 @@ const PermissionOverwrites = require('./PermissionOverwrites');
const Util = require('../util/Util');
const Permissions = require('../util/Permissions');
const Collection = require('../util/Collection');
const Constants = require('../util/Constants');
const { MessageNotificationTypes } = require('../util/Constants');
const { Error, TypeError } = require('../errors');
/**
@@ -474,7 +474,7 @@ class GuildChannel extends Channel {
try {
return this.client.user.guildSettings.get(this.guild.id).channelOverrides.get(this.id).messageNotifications;
} catch (err) {
return Constants.MessageNotificationTypes[3];
return MessageNotificationTypes[3];
}
}

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { Endpoints } = require('../util/Constants');
const Base = require('./Base');
/**
@@ -127,7 +127,7 @@ class Invite extends Base {
* @readonly
*/
get url() {
return Constants.Endpoints.invite(this.client.options.http.invite, this.code);
return Endpoints.invite(this.client.options.http.invite, this.code);
}
/**

View File

@@ -6,7 +6,7 @@ const ClientApplication = require('./ClientApplication');
const Util = require('../util/Util');
const Collection = require('../util/Collection');
const ReactionStore = require('../stores/ReactionStore');
const Constants = require('../util/Constants');
const { MessageTypes } = require('../util/Constants');
const Permissions = require('../util/Permissions');
const GuildMember = require('./GuildMember');
const Base = require('./Base');
@@ -40,7 +40,7 @@ class Message extends Base {
* The type of the message
* @type {MessageType}
*/
this.type = Constants.MessageTypes[data.type];
this.type = MessageTypes[data.type];
/**
* The content of the message

View File

@@ -1,4 +1,5 @@
const Collector = require('./interfaces/Collector');
const { Events } = require('../util/Constants');
/**
* @typedef {CollectorOptions} MessageCollectorOptions
@@ -36,14 +37,14 @@ class MessageCollector extends Collector {
for (const message of messages.values()) this.handleDispose(message);
}).bind(this);
this.client.on('message', this.handleCollect);
this.client.on('messageDelete', this.handleDispose);
this.client.on('messageDeleteBulk', bulkDeleteListener);
this.client.on(Events.MESSAGE_CREATE, this.handleCollect);
this.client.on(Events.MESSAGE_DELETE, this.handleDispose);
this.client.on(Events.MESSAGE_BULK_DELETE, bulkDeleteListener);
this.once('end', () => {
this.client.removeListener('message', this.handleCollect);
this.client.removeListener('messageDelete', this.handleDispose);
this.client.removeListener('messageDeleteBulk', bulkDeleteListener);
this.client.removeListener(Events.MESSAGE_CREATE, this.handleCollect);
this.client.removeListener(Events.MESSAGE_DELETE, this.handleDispose);
this.client.removeListener(Events.MESSAGE_BULK_DELETE, bulkDeleteListener);
});
}

View File

@@ -1,4 +1,4 @@
const Constants = require('../util/Constants');
const { ActivityTypes } = require('../util/Constants');
/**
* Represents a user's presence.
@@ -67,7 +67,7 @@ class Activity {
* The type of the activity status
* @type {ActivityType}
*/
this.type = Constants.ActivityTypes[data.type];
this.type = ActivityTypes[data.type];
/**
* If the activity is being streamed, a link to the stream

View File

@@ -1,5 +1,6 @@
const Collector = require('./interfaces/Collector');
const Collection = require('../util/Collection');
const { Events } = require('../util/Constants');
/**
* @typedef {CollectorOptions} ReactionCollectorOptions
@@ -41,14 +42,14 @@ class ReactionCollector extends Collector {
this.empty = this.empty.bind(this);
this.client.on('messageReactionAdd', this.handleCollect);
this.client.on('messageReactionRemove', this.handleDispose);
this.client.on('messageReactionRemoveAll', this.empty);
this.client.on(Events.MESSAGE_REACTION_ADD, this.handleCollect);
this.client.on(Events.MESSAGE_REACTION_REMOVE, this.handleDispose);
this.client.on(Events.MESSAGE_REACTION_REMOVE_ALL, this.empty);
this.once('end', () => {
this.client.removeListener('messageReactionAdd', this.handleCollect);
this.client.removeListener('messageReactionRemove', this.handleDispose);
this.client.removeListener('messageReactionRemoveAll', this.empty);
this.client.removeListener(Events.MESSAGE_REACTION_ADD, this.handleCollect);
this.client.removeListener(Events.MESSAGE_REACTION_REMOVE, this.handleDispose);
this.client.removeListener(Events.MESSAGE_REACTION_REMOVE_ALL, this.empty);
});
this.on('collect', (collected, reaction, user) => {

View File

@@ -1,7 +1,6 @@
const Long = require('long');
const snekfetch = require('snekfetch');
const Constants = require('./Constants');
const ConstantsHttp = Constants.DefaultOptions.http;
const { Colors, DefaultOptions, Endpoints } = require('./Constants');
const { Error: DiscordError, RangeError, TypeError } = require('../errors');
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
@@ -60,7 +59,7 @@ class Util {
static fetchRecommendedShards(token, guildsPerShard = 1000) {
return new Promise((resolve, reject) => {
if (!token) throw new DiscordError('TOKEN_MISSING');
snekfetch.get(`${ConstantsHttp.api}/v${ConstantsHttp.version}${Constants.Endpoints.botGateway}`)
snekfetch.get(`${DefaultOptions.http.api}/v${DefaultOptions.http.version}${Endpoints.botGateway}`)
.set('Authorization', `Bot ${token.replace(/^Bot\s*/i, '')}`)
.end((err, res) => {
if (err) reject(err);
@@ -278,7 +277,7 @@ class Util {
static resolveColor(color) {
if (typeof color === 'string') {
if (color === 'RANDOM') return Math.floor(Math.random() * (0xFFFFFF + 1));
color = Constants.Colors[color] || parseInt(color.replace('#', ''), 16);
color = Colors[color] || parseInt(color.replace('#', ''), 16);
} else if (color instanceof Array) {
color = (color[0] << 16) + (color[1] << 8) + color[2];
}