Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

discord.js

Package Overview
Dependencies
Maintainers
1
Versions
1745
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

discord.js - npm Package Compare versions

Comparing version 5.0.0 to 5.0.1

.gitattributes

0

gruntfile.js

@@ -0,0 +0,0 @@ module.exports = function (grunt) {

@@ -1,58 +0,882 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var InternalClient=require("./InternalClient.js");var EventEmitter=require("events");var Client=(function(_EventEmitter){_inherits(Client,_EventEmitter); /*
this class is an interface for the internal
client.
*/function Client(options){_classCallCheck(this,Client);_EventEmitter.call(this);this.options = options || {};this.internal = new InternalClient(this);} // def login
Client.prototype.login = function login(email,password){var cb=arguments.length <= 2 || arguments[2] === undefined?function(err,token){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.login(email,password).then(function(token){cb(null,token);resolve(token);})["catch"](function(e){cb(e);reject(e);});});}; // def logout
Client.prototype.logout = function logout(){var cb=arguments.length <= 0 || arguments[0] === undefined?function(err){}:arguments[0];var self=this;return new Promise(function(resolve,reject){self.internal.logout().then(function(){cb();resolve();})["catch"](function(e){cb(e);reject(e);});});}; // def sendMessage
Client.prototype.sendMessage = function sendMessage(where,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(e,m){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.sendMessage(where,content,options).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def sendTTSMessage
Client.prototype.sendTTSMessage = function sendTTSMessage(where,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function(e,m){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.sendMessage(where,content,{tts:true}).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def reply
Client.prototype.reply = function reply(where,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(e,m){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}var msg=self.internal.resolver.resolveMessage(where);if(msg){content = msg.author + ", " + content;self.internal.sendMessage(msg,content,options).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});}else {var err=new Error("Destination not resolvable to a message!");callback(err);reject(err);}});}; // def replyTTS
Client.prototype.replyTTS = function replyTTS(where,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function(){}:arguments[2];return new Promise(function(resolve,reject){self.reply(where,content,{tts:true}).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def deleteMessage
Client.prototype.deleteMessage = function deleteMessage(msg){var options=arguments.length <= 1 || arguments[1] === undefined?{}:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(e){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.deleteMessage(msg,options).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def updateMessage
Client.prototype.updateMessage = function updateMessage(msg,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,msg){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.updateMessage(msg,content,options).then(function(msg){callback(null,msg);resolve(msg);})["catch"](function(e){callback(e);reject(e);});});}; // def getChannelLogs
Client.prototype.getChannelLogs = function getChannelLogs(where){var limit=arguments.length <= 1 || arguments[1] === undefined?500:arguments[1];var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,logs){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.getChannelLogs(where,limit,options).then(function(logs){callback(null,logs);resolve(logs);})["catch"](function(e){callback(e);reject(e);});});}; // def getBans
Client.prototype.getBans = function getBans(where){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,bans){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.getBans(where).then(function(bans){callback(null,bans);resolve(bans);})["catch"](function(e){callback(e);reject(e);});});}; // def sendFile
Client.prototype.sendFile = function sendFile(where,attachment){var name=arguments.length <= 2 || arguments[2] === undefined?"image.png":arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,m){}:arguments[3];var self=this;return new Promise(function(resolve,reject){self.internal.sendFile(where,attachment,name).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def joinServer
Client.prototype.joinServer = function joinServer(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,srv){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.joinServer(invite).then(function(srv){callback(null,srv);resolve(srv);})["catch"](function(e){callback(e);reject(e);});});}; // def createServer
Client.prototype.createServer = function createServer(name){var region=arguments.length <= 1 || arguments[1] === undefined?"london":arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,srv){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.createServer(name,region).then(function(srv){callback(null,srv);resolve(srv);})["catch"](function(e){callback(e);reject(e);});});}; // def leaveServer
Client.prototype.leaveServer = function leaveServer(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.leaveServer(server).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def createChannel
Client.prototype.createChannel = function createChannel(server,name){var type=arguments.length <= 2 || arguments[2] === undefined?"text":arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,channel){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof type === "function"){ // options is the callback
callback = type;}self.internal.createChannel(server,name,type).then(function(channel){callback(channel);resolve(channel);})["catch"](function(e){callback(e);reject(e);});});}; // def deleteChannel
Client.prototype.deleteChannel = function deleteChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.deleteChannel(channel).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def banMember
Client.prototype.banMember = function banMember(user,server){var length=arguments.length <= 2 || arguments[2] === undefined?1:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof length === "function"){ // length is the callback
callback = length;}self.internal.banMember(user,server,length).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def unbanMember
Client.prototype.unbanMember = function unbanMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.unbanMember(user,server).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def kickMember
Client.prototype.kickMember = function kickMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.kickMember(user,server).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def createRole
Client.prototype.createRole = function createRole(server){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,res){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof data === "function"){ // data is the callback
callback = data;}self.internal.createRole(server,data).then(function(role){callback(null,role);resolve(role);})["catch"](function(e){callback(e);reject(e);});});}; //def updateRole
Client.prototype.updateRole = function updateRole(role){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,res){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof data === "function"){ // data is the callback
callback = data;}self.internal.updateRole(role,data).then(function(role){callback(null,role);resolve(role);})["catch"](function(e){callback(e);reject(e);});});}; //def deleteRole
Client.prototype.deleteRole = function deleteRole(role){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.deleteRole(role).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def addMemberToRole
Client.prototype.addMemberToRole = function addMemberToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.addMemberToRole(member,role).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def addUserToRole
Client.prototype.addUserToRole = function addUserToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];return this.addMemberToRole(member,role,callback);}; // def removeMemberFromRole
Client.prototype.removeMemberFromRole = function removeMemberFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.removeMemberFromRole(member,role).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def removeUserFromRole
Client.prototype.removeUserFromRole = function removeUserFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];return this.removeUserFromRole(member,role,callback);}; // def createInvite
Client.prototype.createInvite = function createInvite(chanServ,options){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,invite){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // length is the callback
callback = options;}self.internal.createInvite(chanServ,options).then(function(invite){callback(null,invite);resolve(invite);})["catch"](function(e){callback(e);reject(e);});});}; // def deleteInvite
Client.prototype.deleteInvite = function deleteInvite(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.deleteInvite(invite).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def overwritePermissions
Client.prototype.overwritePermissions = function overwritePermissions(channel,role){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err){}:arguments[3];var self=this;return new Promise(function(resolve,reject){self.internal.overwritePermissions(channel,role,options).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def setStatus
Client.prototype.setStatus = function setStatus(idleStatus,gameID){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof gameID === "function"){ // gameID is the callback
callback = gameID;}else if(typeof idleStatus === "function"){ // idleStatus is the callback
callback = idleStatus;}self.internal.setStatus(idleStatus,gameID).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def sendTyping
Client.prototype.sendTyping = function sendTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.sendTyping(channel).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def setTopic
Client.prototype.setTopic = function setTopic(channel,topic){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.setTopic(channel,topic).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def setChannelName
Client.prototype.setChannelName = function setChannelName(channel,name){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.setChannelName(channel,name).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def setChannelNameAndTopic
Client.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(channel,name,topic){var callback=arguments.length <= 3 || arguments[3] === undefined?function(err){}:arguments[3];var self=this;return new Promise(function(resolve,reject){self.internal.setChannelNameAndTopic(channel,name,topic).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def updateChannel
Client.prototype.updateChannel = function updateChannel(channel,data){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.updateChannel(channel,data).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def startTyping
Client.prototype.startTyping = function startTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.startTyping(channel).then(function(){callback(null);resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def stopTyping
Client.prototype.stopTyping = function stopTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.stopTyping(channel).then(function(){callback(null);resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def updateDetails
Client.prototype.updateDetails = function updateDetails(details){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.updateDetails(details).then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});}; //def setUsername
Client.prototype.setUsername = function setUsername(name){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.setUsername(name).then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});}; //def setAvatar
Client.prototype.setAvatar = function setAvatar(avatar){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.setAvatar(avatar).then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});}; //def joinVoiceChannel
Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.joinVoiceChannel(channel).then(function(chan){callback(null,chan);resolve(chan);})["catch"](function(err){callback(err);reject(err);});});}; // def leaveVoiceChannel
Client.prototype.leaveVoiceChannel = function leaveVoiceChannel(){var callback=arguments.length <= 0 || arguments[0] === undefined?function(err){}:arguments[0];var self=this;return new Promise(function(resolve,reject){self.internal.leaveVoiceChannel().then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});};_createClass(Client,[{key:"users",get:function get(){return this.internal.users;}},{key:"channels",get:function get(){return this.internal.channels;}},{key:"servers",get:function get(){return this.internal.servers;}},{key:"privateChannels",get:function get(){return this.internal.private_channels;}},{key:"voiceConnection",get:function get(){return this.internal.voiceConnection;}},{key:"readyTime",get:function get(){return this.internal.readyTime;}},{key:"uptime",get:function get(){return this.internal.uptime;}},{key:"user",get:function get(){return this.internal.user;}}]);return Client;})(EventEmitter);module.exports = Client;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var InternalClient = require("./InternalClient.js");
var EventEmitter = require("events");
var Client = (function (_EventEmitter) {
_inherits(Client, _EventEmitter);
/*
this class is an interface for the internal
client.
*/
function Client(options) {
_classCallCheck(this, Client);
_EventEmitter.call(this);
this.options = options || {};
this.internal = new InternalClient(this);
}
// def login
Client.prototype.login = function login(email, password) {
var cb = arguments.length <= 2 || arguments[2] === undefined ? function (err, token) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.login(email, password).then(function (token) {
cb(null, token);
resolve(token);
})["catch"](function (e) {
cb(e);
reject(e);
});
});
};
// def logout
Client.prototype.logout = function logout() {
var cb = arguments.length <= 0 || arguments[0] === undefined ? function (err) {} : arguments[0];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.logout().then(function () {
cb();
resolve();
})["catch"](function (e) {
cb(e);
reject(e);
});
});
};
// def sendMessage
Client.prototype.sendMessage = function sendMessage(where, content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (e, m) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.sendMessage(where, content, options).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def sendTTSMessage
Client.prototype.sendTTSMessage = function sendTTSMessage(where, content) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (e, m) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.sendMessage(where, content, { tts: true }).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def reply
Client.prototype.reply = function reply(where, content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (e, m) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
var msg = self.internal.resolver.resolveMessage(where);
if (msg) {
content = msg.author + ", " + content;
self.internal.sendMessage(msg, content, options).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
} else {
var err = new Error("Destination not resolvable to a message!");
callback(err);
reject(err);
}
});
};
// def replyTTS
Client.prototype.replyTTS = function replyTTS(where, content) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function () {} : arguments[2];
return new Promise(function (resolve, reject) {
self.reply(where, content, { tts: true }).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def deleteMessage
Client.prototype.deleteMessage = function deleteMessage(msg) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (e) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.deleteMessage(msg, options).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateMessage
Client.prototype.updateMessage = function updateMessage(msg, content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, msg) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.updateMessage(msg, content, options).then(function (msg) {
callback(null, msg);
resolve(msg);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def getChannelLogs
Client.prototype.getChannelLogs = function getChannelLogs(where) {
var limit = arguments.length <= 1 || arguments[1] === undefined ? 500 : arguments[1];
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, logs) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.getChannelLogs(where, limit, options).then(function (logs) {
callback(null, logs);
resolve(logs);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def getBans
Client.prototype.getBans = function getBans(where) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, bans) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.getBans(where).then(function (bans) {
callback(null, bans);
resolve(bans);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def sendFile
Client.prototype.sendFile = function sendFile(where, attachment) {
var name = arguments.length <= 2 || arguments[2] === undefined ? "image.png" : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, m) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.sendFile(where, attachment, name).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def joinServer
Client.prototype.joinServer = function joinServer(invite) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, srv) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.joinServer(invite).then(function (srv) {
callback(null, srv);
resolve(srv);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def createServer
Client.prototype.createServer = function createServer(name) {
var region = arguments.length <= 1 || arguments[1] === undefined ? "london" : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, srv) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.createServer(name, region).then(function (srv) {
callback(null, srv);
resolve(srv);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def leaveServer
Client.prototype.leaveServer = function leaveServer(server) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.leaveServer(server).then(function () {
callback();resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
// def createChannel
Client.prototype.createChannel = function createChannel(server, name) {
var type = arguments.length <= 2 || arguments[2] === undefined ? "text" : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, channel) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof type === "function") {
// options is the callback
callback = type;
}
self.internal.createChannel(server, name, type).then(function (channel) {
callback(channel);resolve(channel);
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
// def deleteChannel
Client.prototype.deleteChannel = function deleteChannel(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.deleteChannel(channel).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def banMember
Client.prototype.banMember = function banMember(user, server) {
var length = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof length === "function") {
// length is the callback
callback = length;
}
self.internal.banMember(user, server, length).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def unbanMember
Client.prototype.unbanMember = function unbanMember(user, server) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.unbanMember(user, server).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def kickMember
Client.prototype.kickMember = function kickMember(user, server) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.kickMember(user, server).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def createRole
Client.prototype.createRole = function createRole(server) {
var data = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, res) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof data === "function") {
// data is the callback
callback = data;
}
self.internal.createRole(server, data).then(function (role) {
callback(null, role);
resolve(role);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateRole
Client.prototype.updateRole = function updateRole(role) {
var data = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, res) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof data === "function") {
// data is the callback
callback = data;
}
self.internal.updateRole(role, data).then(function (role) {
callback(null, role);
resolve(role);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def deleteRole
Client.prototype.deleteRole = function deleteRole(role) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.deleteRole(role).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def addMemberToRole
Client.prototype.addMemberToRole = function addMemberToRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.addMemberToRole(member, role).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def addUserToRole
Client.prototype.addUserToRole = function addUserToRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
return this.addMemberToRole(member, role, callback);
};
// def removeMemberFromRole
Client.prototype.removeMemberFromRole = function removeMemberFromRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.removeMemberFromRole(member, role).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def removeUserFromRole
Client.prototype.removeUserFromRole = function removeUserFromRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
return this.removeUserFromRole(member, role, callback);
};
// def createInvite
Client.prototype.createInvite = function createInvite(chanServ, options) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, invite) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// length is the callback
callback = options;
}
self.internal.createInvite(chanServ, options).then(function (invite) {
callback(null, invite);
resolve(invite);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def deleteInvite
Client.prototype.deleteInvite = function deleteInvite(invite) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.deleteInvite(invite).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def overwritePermissions
Client.prototype.overwritePermissions = function overwritePermissions(channel, role) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.overwritePermissions(channel, role, options).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def setStatus
Client.prototype.setStatus = function setStatus(idleStatus, gameID) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof gameID === "function") {
// gameID is the callback
callback = gameID;
} else if (typeof idleStatus === "function") {
// idleStatus is the callback
callback = idleStatus;
}
self.internal.setStatus(idleStatus, gameID).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def sendTyping
Client.prototype.sendTyping = function sendTyping(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.sendTyping(channel).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def setTopic
Client.prototype.setTopic = function setTopic(channel, topic) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setTopic(channel, topic).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def setChannelName
Client.prototype.setChannelName = function setChannelName(channel, name) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setChannelName(channel, name).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def setChannelNameAndTopic
Client.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(channel, name, topic) {
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setChannelNameAndTopic(channel, name, topic).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateChannel
Client.prototype.updateChannel = function updateChannel(channel, data) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.updateChannel(channel, data).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def startTyping
Client.prototype.startTyping = function startTyping(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.startTyping(channel).then(function () {
callback(null);
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def stopTyping
Client.prototype.stopTyping = function stopTyping(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.stopTyping(channel).then(function () {
callback(null);
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateDetails
Client.prototype.updateDetails = function updateDetails(details) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.updateDetails(details).then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
//def setUsername
Client.prototype.setUsername = function setUsername(name) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setUsername(name).then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
//def setAvatar
Client.prototype.setAvatar = function setAvatar(avatar) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setAvatar(avatar).then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
//def joinVoiceChannel
Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.joinVoiceChannel(channel).then(function (chan) {
callback(null, chan);
resolve(chan);
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
// def leaveVoiceChannel
Client.prototype.leaveVoiceChannel = function leaveVoiceChannel() {
var callback = arguments.length <= 0 || arguments[0] === undefined ? function (err) {} : arguments[0];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.leaveVoiceChannel().then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
Client.prototype.setStatusIdle = function setStatusIdle() {
this.setStatus("idle");
};
Client.prototype.setStatusOnline = function setStatusOnline() {
var cb = arguments.length <= 0 || arguments[0] === undefined ? function (err) {} : arguments[0];
this.setStatus("online");
};
Client.prototype.setStatusActive = function setStatusActive() {
this.setStatusOnline();
};
Client.prototype.setStatusHere = function setStatusHere() {
this.setStatusOnline();
};
Client.prototype.setStatusAvailable = function setStatusAvailable() {
this.setStatusOnline();
};
Client.prototype.setStatusAway = function setStatusAway() {
this.setStatusIdle();
};
Client.prototype.setPlayingGame = function setPlayingGame(game) {
this.setStatus(null, game);
};
_createClass(Client, [{
key: "users",
get: function get() {
return this.internal.users;
}
}, {
key: "channels",
get: function get() {
return this.internal.channels;
}
}, {
key: "servers",
get: function get() {
return this.internal.servers;
}
}, {
key: "privateChannels",
get: function get() {
return this.internal.private_channels;
}
}, {
key: "voiceConnection",
get: function get() {
return this.internal.voiceConnection;
}
}, {
key: "readyTime",
get: function get() {
return this.internal.readyTime;
}
}, {
key: "uptime",
get: function get() {
return this.internal.uptime;
}
}, {
key: "user",
get: function get() {
return this.internal.user;
}
}]);
return Client;
})(EventEmitter);
module.exports = Client;

@@ -1,1 +0,7 @@

"use strict";exports.IDLE = 0;exports.LOGGING_IN = 1;exports.LOGGED_IN = 2;exports.READY = 3;exports.DISCONNECTED = 4;
"use strict";
exports.IDLE = 0;
exports.LOGGING_IN = 1;
exports.LOGGED_IN = 2;
exports.READY = 3;
exports.DISCONNECTED = 4;

@@ -1,69 +0,1599 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var EventEmitter=require("events");var request=require("superagent");var WebSocket=require("ws");var ConnectionState=require("./ConnectionState.js");var Constants=require("../Constants.js"),Endpoints=Constants.Endpoints,PacketType=Constants.PacketType;var Cache=require("../Util/Cache.js");var Resolver=require("./Resolver/Resolver.js");var User=require("../Structures/User.js"),Channel=require("../Structures/Channel.js"),TextChannel=require("../Structures/TextChannel.js"),VoiceChannel=require("../Structures/VoiceChannel.js"),PMChannel=require("../Structures/PMChannel.js"),Server=require("../Structures/Server.js"),Message=require("../Structures/Message.js"),Role=require("../Structures/Role.js"),Invite=require("../Structures/Invite.js"),VoiceConnection=require("../Voice/VoiceConnection.js");var zlib;var InternalClient=(function(){function InternalClient(discordClient){_classCallCheck(this,InternalClient);this.client = discordClient;this.state = ConnectionState.IDLE;this.websocket = null;if(this.client.options.compress){zlib = require("zlib");} // creates 4 caches with discriminators based on ID
this.users = new Cache();this.channels = new Cache();this.servers = new Cache();this.private_channels = new Cache();this.typingIntervals = [];this.voiceConnection = null;this.resolver = new Resolver(this);this.readyTime = null;} //def leaveVoiceChannel
InternalClient.prototype.leaveVoiceChannel = function leaveVoiceChannel(){var self=this;return new Promise(function(resolve,reject){if(self.voiceConnection){self.voiceConnection.destroy();self.voiceConnection = null;resolve();}else {resolve();}});}; //def joinVoiceChannel
InternalClient.prototype.joinVoiceChannel = function joinVoiceChannel(chann){var self=this;return new Promise(function(resolve,reject){var channel=self.resolver.resolveVoiceChannel(chann);if(channel){var next=function next(){var session,token,server=channel.server,endpoint;var check=function check(m){var data=JSON.parse(m);if(data.t === "VOICE_STATE_UPDATE"){session = data.d.session_id;}else if(data.t === "VOICE_SERVER_UPDATE"){token = data.d.token;endpoint = data.d.endpoint;var chan=self.voiceConnection = new VoiceConnection(channel,self.client,session,token,server,endpoint);chan.on("ready",function(){return resolve(chan);});chan.on("error",reject);self.client.emit("debug","removed temporary voice websocket listeners");self.websocket.removeListener("message",check);}};self.websocket.on("message",check);self.sendWS({op:4,d:{"guild_id":server.id,"channel_id":channel.id,"self_mute":false,"self_deaf":false}});};self.leaveVoiceChannel().then(next);}else {reject(new Error("voice channel does not exist"));}});}; // def createServer
InternalClient.prototype.createServer = function createServer(name){var region=arguments.length <= 1 || arguments[1] === undefined?"london":arguments[1];var self=this;return new Promise(function(resolve,reject){name = self.resolver.resolveString(name);request.post(Endpoints.SERVERS).set("authorization",self.token).send({name:name,region:region}).end(function(err,res){if(err){reject(new Error(err));}else { // valid server, wait until it is cached
var inter=setInterval(function(){if(self.servers.get("id",res.body.id)){clearInterval(inter);resolve(self.servers.get("id",res.body.id));}},20);}});});}; //def joinServer
InternalClient.prototype.joinServer = function joinServer(invite){var self=this;return new Promise(function(resolve,reject){invite = self.resolver.resolveInviteID(invite);if(invite){request.post(Endpoints.INVITE(invite)).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else { // valid server, wait until it is received via ws and cached
var inter=setInterval(function(){if(self.servers.get("id",res.body.guild.id)){clearInterval(inter);resolve(self.servers.get("id",res.body.guild.id));}},20);}});}else {reject(new Error("Not a valid invite"));}});}; //def leaveServer
InternalClient.prototype.leaveServer = function leaveServer(srv){var self=this;return new Promise(function(resolve,reject){var server=self.resolver.resolveServer(srv);if(server){request.del(Endpoints.SERVER(server.id)).set("authorization",self.token).end(function(err,res){if(err){reject(new Error(err));}else { // remove channels of server then the server
for(var _iterator=server.channels,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var chan=_ref;self.channels.remove(chan);} // remove server
self.servers.remove(server);resolve();}});}else {reject(new Error("server did not resolve"));}});}; // def login
InternalClient.prototype.login = function login(email,password){var self=this;var client=self.client;return new Promise(function(resolve,reject){if(self.state === ConnectionState.DISCONNECTED || self.state === ConnectionState.IDLE){self.state = ConnectionState.LOGGING_IN;request.post(Endpoints.LOGIN).send({email:email,password:password}).end(function(err,res){if(err){self.state = ConnectionState.DISCONNECTED;self.websocket = null;client.emit("disconnected");reject(new Error(err));}else {var token=res.body.token;self.state = ConnectionState.LOGGED_IN;self.token = token;self.email = email;self.password = password;self.getGateway().then(function(url){self.createWS(url);resolve(token);})["catch"](function(e){self.state = ConnectionState.DISCONNECTED;client.emit("disconnected");reject(new Error(err));});}});}else {reject(new Error("already logging in/logged in/ready!"));}});}; // def logout
InternalClient.prototype.logout = function logout(){var _this=this;var self=this;return new Promise(function(resolve,reject){if(self.state === ConnectionState.DISCONNECTED || self.state === ConnectionState.IDLE){reject(new Error("Client is not logged in!"));return;}request.post(Endpoints.LOGOUT).set("authorization",self.token).end(function(err,res){if(err){reject(new Error(err));}else {if(_this.websocket){_this.websocket.close();_this.websocket = null;}self.token = null;self.email = null;self.password = null;self.state = ConnectionState.DISCONNECTED;resolve();}});});}; // def startPM
InternalClient.prototype.startPM = function startPM(resUser){var self=this;return new Promise(function(resolve,reject){var user=self.resolver.resolveUser(resUser);if(user){ // start the PM
request.post("" + Endpoints.USER_CHANNELS(user.id)).set("authorization",self.token).send({recipient_id:user.id}).end(function(err,res){if(err){reject(new Error(err));}else {resolve(self.private_channels.add(new PMChannel(res.body,self.client)));}});}else {reject(new Error("Unable to resolve resUser to a User"));}});}; // def getGateway
InternalClient.prototype.getGateway = function getGateway(){var self=this;return new Promise(function(resolve,reject){request.get(Endpoints.GATEWAY).set("authorization",self.token).end(function(err,res){if(err)reject(err);else resolve(res.body.url);});});}; // def sendMessage
InternalClient.prototype.sendMessage = function sendMessage(where,_content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(where).then(next)["catch"](function(e){return reject(new Error("Error resolving destination - " + e));});function next(destination){ //var destination;
var content=self.resolver.resolveString(_content);var mentions=self.resolver.resolveMentions(content);request.post(Endpoints.CHANNEL_MESSAGES(destination.id)).set("authorization",self.token).send({content:content,mentions:mentions,tts:options.tts}).end(function(err,res){if(err){reject(new Error(err));}else {resolve(destination.messages.add(new Message(res.body,destination,self.client)));}});}});}; // def deleteMessage
InternalClient.prototype.deleteMessage = function deleteMessage(_message){var options=arguments.length <= 1 || arguments[1] === undefined?{}:arguments[1];var self=this;return new Promise(function(resolve,reject){var message=self.resolver.resolveMessage(_message);if(message){var deleteMsg=function deleteMsg(){request.del(Endpoints.CHANNEL_MESSAGE(message.channel.id,message.id)).set("authorization",self.token).end(function(err,res){if(err){reject(new Error(err));}else {message.channel.messages.remove(message);resolve();}});};if(options.wait){setTimeout(deleteMsg,options.wait);}else {deleteMsg();}}else {reject(new Error("Supplied message did not resolve to a message!"));}});}; // def updateMessage
InternalClient.prototype.updateMessage = function updateMessage(msg,_content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var self=this;return new Promise(function(resolve,reject){var message=self.resolver.resolveMessage(msg);if(message){var content=self.resolver.resolveString(_content);var mentions=self.resolver.resolveMentions(content);request.patch(Endpoints.CHANNEL_MESSAGE(message.channel.id,message.id)).set("authorization",self.token).send({content:content,tts:options.tts,mentions:mentions}).end(function(err,res){if(err){reject(new Error(err));}else {resolve(message.channel.messages.update(message,new Message(res.body,message.channel,self.client)));}});}else {reject(new Error("Supplied message did not resolve to a message!"));}});}; // def sendFile
InternalClient.prototype.sendFile = function sendFile(where,_file){var name=arguments.length <= 2 || arguments[2] === undefined?"image.png":arguments[2];var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(where).then(next)["catch"](function(e){return reject(new Error("couldn't resolve to channel - " + e));});function next(channel){var file=self.resolver.resolveFile(_file);request.post(Endpoints.CHANNEL_MESSAGES(channel.id)).set("authorization",self.token).attach("file",file,name).end(function(err,res){if(err){reject(new Error(err));}else {resolve(channel.messages.add(new Message(res.body,channel,self.client)));}});}});}; // def getChannelLogs
InternalClient.prototype.getChannelLogs = function getChannelLogs(_channel){var limit=arguments.length <= 1 || arguments[1] === undefined?500:arguments[1];var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(_channel).then(next)["catch"](function(e){return reject(new Error("couldn't resolve to channel - " + e));});function next(channel){if(options.before)options.before = self.resolver.resolveMessage(options.before);if(options.after)options.after = self.resolver.resolveMessage(options.after);var params=[];if(options.before)params.push("before=" + options.before.id);if(options.after)params.push("after=" + options.after.id);var joinedParams=params.join();if(joinedParams !== "")joinedParams = "&" + params.join();request.get(Endpoints.CHANNEL_MESSAGES(channel.id) + "?limit=" + limit + joinedParams).set("authorization",self.token).end(function(err,res){if(err){reject(new Error(err));}else {var logs=[];res.body.forEach(function(msg){logs.push(channel.messages.add(new Message(msg,channel,self.client)));});resolve(logs);}});}});}; // def getBans
InternalClient.prototype.getBans = function getBans(server){var self=this;return new Promise(function(resolve,reject){server = self.resolver.resolveServer(server);request.get("" + Endpoints.SERVER_BANS(server.id)).set("authorization",self.token).end(function(err,res){if(err){reject(new Error(err));}else {var bans=[];res.body.forEach(function(ban){bans.push(self.users.add(new User(ban.user,self.client)));});resolve(bans);}});});}; // def createChannel
InternalClient.prototype.createChannel = function createChannel(server,name){var type=arguments.length <= 2 || arguments[2] === undefined?"text":arguments[2];var self=this;return new Promise(function(resolve,reject){server = self.resolver.resolveServer(server);request.post(Endpoints.SERVER_CHANNELS(server.id)).set("authorization",self.token).send({name:name,type:type}).end(function(err,res){if(err){reject(err);}else {var channel;if(res.body.type === "text"){channel = new TextChannel(res.body,self.client,server);}else {channel = new VoiceChannel(res.body,self.client,server);}resolve(server.channels.add(self.channels.add(channel)));}});});}; // def deleteChannel
InternalClient.prototype.deleteChannel = function deleteChannel(_channel){var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(_channel).then(next)["catch"](reject);function next(channel){request.del(Endpoints.CHANNEL(channel.id)).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {channel.server.channels.remove(channel);self.channels.remove(channel);resolve();}});}});}; // def banMember
InternalClient.prototype.banMember = function banMember(user,server){var length=arguments.length <= 2 || arguments[2] === undefined?1:arguments[2];var self=this;return new Promise(function(resolve,reject){user = self.resolver.resolveUser(user);server = self.resolver.resolveServer(server);request.put(Endpoints.SERVER_BANS(server.id) + "/" + user.id + "/?delete-message-days=" + length).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {resolve();}});});}; // def unbanMember
InternalClient.prototype.unbanMember = function unbanMember(user,server){var self=this;return new Promise(function(resolve,reject){server = self.resolver.resolveServer(server);user = self.resolver.resolveUser(user);request.del(Endpoints.SERVER_BANS(server.id) + "/" + user.id).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {resolve();}});});}; // def kickMember
InternalClient.prototype.kickMember = function kickMember(user,server){var self=this;return new Promise(function(resolve,reject){user = self.resolver.resolveUser(user);server = self.resolver.resolveServer(server);request.del(Endpoints.SERVER_MEMBERS(server.id) + "/" + user.id).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {resolve();}});});}; // def createRole
InternalClient.prototype.createRole = function createRole(server,data){var self=this;return new Promise(function(resolve,reject){server = self.resolver.resolveServer(server);request.post(Endpoints.SERVER_ROLES(server.id)).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {var role=server.roles.add(new Role(res.body,server,self.client));if(data){self.updateRole(role,data).then(resolve)["catch"](reject);}else {resolve(role);}}});});}; // def updateRole
InternalClient.prototype.updateRole = function updateRole(role,data){var self=this;data = data || {};data.permissions = data.permissions || [];return new Promise(function(resolve,reject){var server=self.resolver.resolveServer(role.server);var permissions=0;for(var _iterator2=data.permissions,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var perm=_ref2;if(perm instanceof String || typeof perm === "string"){permissions |= Constants.Permissions[perm] || 0;}else {permissions |= perm;}}data.color = data.color || 0;request.patch(Endpoints.SERVER_ROLES(server.id) + "/" + role.id).set("authorization",self.token).send({color:data.color || role.color,hoist:data.hoist || role.hoist,name:data.name || role.name,permissions:permissions}).end(function(err,res){if(err){reject(err);}else {var nrole=new Role(res.body,server,self.client);resolve(server.roles.update(role,nrole));}});});}; // def deleteRole
InternalClient.prototype.deleteRole = function deleteRole(role){var self=this;return new Promise(function(resolve,reject){request.del(Endpoints.SERVER_ROLES(role.server.id) + "/" + role.id).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {resolve(); // the ws cache will handle it
// role.server.roles.remove(role);
}});});}; //def addMemberToRole
InternalClient.prototype.addMemberToRole = function addMemberToRole(member,role){var self=this;return new Promise(function(resolve,reject){member = self.resolver.resolveUser(member);if(!member || !role){reject(new Error("member/role not in server"));return;}if(role.server.memberMap[member.id]){var roleIDS=role.server.memberMap[member.id].roles.map(function(r){return r.id;}).concat(role.id);request.patch(Endpoints.SERVER_MEMBERS(role.server.id) + "/" + member.id).set("authorization",self.token).send({roles:roleIDS}).end(function(err){if(err){reject(err);}else {resolve();}});}else {reject(new Error("member not in server"));}});}; //def removeMemberFromRole
InternalClient.prototype.removeMemberFromRole = function removeMemberFromRole(member,role){var self=this;return new Promise(function(resolve,reject){member = self.resolver.resolveUser(member);if(!member || !role){reject(new Error("member/role not in server"));return;}if(role.server.memberMap[member.id]){var roleIDS=role.server.memberMap[member.id].roles.map(function(r){return r.id;});for(var item in roleIDS) {if(roleIDS[item] === role.id){roleIDS.splice(item,1);}}request.patch(Endpoints.SERVER_MEMBERS(role.server.id) + "/" + member.id).set("authorization",self.token).send({roles:roleIDS}).end(function(err){if(err){reject(err);}else {resolve();}});}else {reject(new Error("member not in server"));}});}; // def createInvite
InternalClient.prototype.createInvite = function createInvite(chanServ,options){var self=this;return new Promise(function(resolve,reject){if(chanServ instanceof Channel){ // do something
}else if(chanServ instanceof Server){ // do something
}else {chanServ = self.resolver.resolveServer(chanServ) || self.resolver.resolveChannel(chanServ);}if(!chanServ){reject(new Error("couldn't resolve where"));return;}if(!options){options = {validate:null};}else {options.max_age = options.maxAge || 0;options.max_uses = options.maxUses || 0;options.temporary = options.temporary || false;options.xkcdpass = options.xkcd || false;}var epoint;if(chanServ instanceof Channel){epoint = Endpoints.CHANNEL_INVITES(chanServ.id);}else {epoint = Endpoints.SERVER_INVITES(chanServ.id);}request.post(epoint).set("authorization",self.token).send(options).end(function(err,res){if(err){reject(err);}else {resolve(new Invite(res.body,self.channels.get("id",res.body.channel.id),self.client));}});});}; //def deleteInvite
InternalClient.prototype.deleteInvite = function deleteInvite(invite){var self=this;return new Promise(function(resolve,reject){invite = self.resolver.resolveInviteID(invite);if(invite){request.del(Endpoints.INVITE(invite)).set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {resolve();}});}else {reject(new Error("Not a valid invite"));}});}; //def overwritePermissions
InternalClient.prototype.overwritePermissions = function overwritePermissions(channel,role,updated){var self=this;return new Promise(function(resolve,reject){channel = self.resolver.resolveChannel(channel)["catch"](reject).then(next);function next(channel){var user;if(role instanceof User){user = role;}var data={};data.allow = 0;data.deny = 0;updated.allow = updated.allow || [];updated.deny = updated.deny || [];if(role instanceof Role){data.id = role.id;data.type = "role";}else if(user){data.id = user.id;data.type = "member";}else {reject(new Error("role incorrect"));return;}for(var perm in updated) {if(updated[perm]){if(perm instanceof String || typeof perm === "string"){data.allow |= Constants.Permissions[perm] || 0;}else {data.allow |= perm;}}else {if(perm instanceof String || typeof perm === "string"){data.deny |= Constants.Permissions[perm] || 0;}else {data.deny |= perm;}}}request.put(Endpoints.CHANNEL_PERMISSIONS(channel.id) + "/" + data.id).set("authorization",self.token).send(data).end(function(err){if(err){reject(err);}else {resolve();}});}});}; //def setStatus
InternalClient.prototype.setStatus = function setStatus(idleStatus,gameID){var self=this;return new Promise(function(resolve,reject){var packet={op:3,d:{idle_since:null,game_id:null}};if(idleStatus){packet.d.idle_since = Date.now();}if(typeof gameID === "number"){packet.d.game_id = gameID;}self.sendWS(packet);resolve();});}; //def sendTyping
InternalClient.prototype.sendTyping = function sendTyping(channel){var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(channel).then(next)["catch"](reject);function next(channel){request.post(Endpoints.CHANNEL(channel.id) + "/typing").set("authorization",self.token).end(function(err,res){if(err){reject(err);}else {resolve();}});}});}; //def startTyping
InternalClient.prototype.startTyping = function startTyping(channel){var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(channel).then(next)["catch"](reject);function next(channel){if(self.typingIntervals[channel.id]){ // typing interval already exists, leave it alone
reject(new Error("Already typing in that channel"));return;}self.sendTyping(channel);self.typingIntervals[channel.id] = setInterval(function(){return self.sendTyping(channel);},4000);}});}; //def stopTyping
InternalClient.prototype.stopTyping = function stopTyping(channel){var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(channel).then(next)["catch"](reject);function next(channel){if(!self.typingIntervals[channel.id]){ // typing interval doesn't exist
reject(new Error("Not typing in that channel"));return;}clearInterval(self.typingIntervals[channel.id]);self.typingIntervals[channel.id] = false;}});}; //def updateDetails
InternalClient.prototype.updateDetails = function updateDetails(data){var self=this;return new Promise(function(resolve,reject){request.patch(Endpoints.ME).set("authorization",self.token).send({avatar:self.resolver.resolveToBase64(data.avatar) || self.user.avatar,email:data.email || self.email,new_password:data.newPassword || null,password:data.password || self.password,username:data.username || self.user.username}).end(function(err){if(err){reject(err);}else {resolve();}});});}; //def setAvatar
InternalClient.prototype.setAvatar = function setAvatar(avatar){return this.updateDetails({avatar:avatar});}; //def setUsername
InternalClient.prototype.setUsername = function setUsername(username){return this.updateDetails({username:username});}; //def setTopic
InternalClient.prototype.setTopic = function setTopic(chann){var topic=arguments.length <= 1 || arguments[1] === undefined?"":arguments[1];var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(chann).then(next)["catch"](reject);function next(channel){request.patch(Endpoints.CHANNEL(channel.id)).set("authorization",self.token).send({name:channel.name,position:channel.position,topic:topic}).end(function(err,res){if(err){reject(err);}else {channel.topic = res.body.topic;resolve();}});}});}; //def setChannelName
InternalClient.prototype.setChannelName = function setChannelName(chann){var name=arguments.length <= 1 || arguments[1] === undefined?"discordjs_is_the_best":arguments[1];var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(chann).then(next)["catch"](reject);function next(channel){request.patch(Endpoints.CHANNEL(channel.id)).set("authorization",self.token).send({name:name,position:channel.position,topic:channel.topic}).end(function(err,res){if(err){reject(err);}else {channel.name = res.body.name;resolve();}});}});}; //def setChannelNameAndTopic
InternalClient.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(chann){var name=arguments.length <= 1 || arguments[1] === undefined?"discordjs_is_the_best":arguments[1];var topic=arguments.length <= 2 || arguments[2] === undefined?"":arguments[2];var self=this;return new Promise(function(resolve,reject){self.resolver.resolveChannel(chann).then(next)["catch"](reject);function next(channel){request.patch(Endpoints.CHANNEL(channel.id)).set("authorization",self.token).send({name:name,position:channel.position,topic:topic}).end(function(err,res){if(err){reject(err);}else {channel.name = res.body.name;channel.topic = res.body.topic;resolve();}});}});}; //def updateChannel
InternalClient.prototype.updateChannel = function updateChannel(chann,data){return this.setChannelNameAndTopic(chann,data.name,data.topic);}; //def ack
InternalClient.prototype.ack = function ack(msg){var self=this;return new Promise(function(resolve,reject){msg = self.resolver.resolveMessage(msg);if(msg){request.post(Endpoints.CHANNEL_MESSAGE(msg.channel.id,msg.id) + "/ack").set("authorization",self.token).end(function(err){if(err){reject(err);}else {resolve();}});}else {reject(new Error("Message does not exist"));}});};InternalClient.prototype.sendWS = function sendWS(object){if(this.websocket)this.websocket.send(JSON.stringify(object));};InternalClient.prototype.createWS = function createWS(url){var self=this;var client=self.client;if(this.websocket)return false;this.websocket = new WebSocket(url);this.websocket.onopen = function(){self.sendWS({op:2,d:{token:self.token,v:3,compress:self.client.options.compress,properties:{"$os":"discord.js","$browser":"discord.js","$device":"discord.js","$referrer":"discord.js","$referring_domain":"discord.js"}}});};this.websocket.onclose = function(){self.websocket = null;self.state = ConnectionState.DISCONNECTED;client.emit("disconnected");};this.websocket.onerror = function(e){client.emit("error",e);};this.websocket.onmessage = function(e){if(e.type === "Binary"){if(!zlib)zlib = require("zlib");e.data = zlib.inflateSync(e.data).toString();}var packet,data;try{packet = JSON.parse(e.data);data = packet.d;}catch(e) {client.emit("error",e);return;}client.emit("raw",packet);switch(packet.t){case PacketType.READY:var startTime=Date.now();self.user = self.users.add(new User(data.user,client));data.guilds.forEach(function(server){self.servers.add(new Server(server,client));});data.private_channels.forEach(function(pm){self.private_channels.add(new PMChannel(pm,client));});self.state = ConnectionState.READY;setInterval(function(){return self.sendWS({op:1,d:Date.now()});},data.heartbeat_interval);client.emit("ready");client.emit("debug","ready packet took " + (Date.now() - startTime) + "ms to process");client.emit("debug","ready with " + self.servers.length + " servers, " + self.channels.length + " channels and " + self.users.length + " users cached.");self.readyTime = Date.now();break;case PacketType.MESSAGE_CREATE: // format: https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-format
var channel=self.channels.get("id",data.channel_id) || self.private_channels.get("id",data.channel_id);if(channel){var msg=channel.messages.add(new Message(data,channel,client));client.emit("message",msg);self.ack(msg);}else {client.emit("warn","message created but channel is not cached");}break;case PacketType.MESSAGE_DELETE: // format https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-delete
var channel=self.channels.get("id",data.channel_id) || self.private_channels.get("id",data.channel_id);if(channel){ // potentially blank
var msg=channel.messages.get("id",data.id);client.emit("messageDeleted",msg);if(msg){channel.messages.remove(msg);}}else {client.emit("warn","message was deleted but channel is not cached");}break;case PacketType.MESSAGE_UPDATE: // format https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-format
var channel=self.channels.get("id",data.channel_id) || self.private_channels.get("id",data.channel_id);if(channel){ // potentially blank
var msg=channel.messages.get("id",data.id);if(msg){ // old message exists
data.nonce = data.nonce || msg.nonce;data.attachments = data.attachments || msg.attachments;data.tts = data.tts || msg.tts;data.embeds = data.embeds || msg.embeds;data.timestamp = data.timestamp || msg.timestamp;data.mention_everyone = data.mention_everyone || msg.everyoneMentioned;data.content = data.content || msg.content;data.mentions = data.mentions || msg.mentions;data.author = data.author || msg.author;var nmsg=channel.messages.update(msg,new Message(data,channel,client));client.emit("messageUpdated",nmsg,msg);}}else {client.emit("warn","message was updated but channel is not cached");}break;case PacketType.SERVER_CREATE:var server=self.servers.get("id",data.id);if(!server){self.servers.add(new Server(data,client));client.emit("serverCreated",server);}break;case PacketType.SERVER_DELETE:var server=self.servers.get("id",data.id);if(server){for(var _iterator3=server.channels,_isArray3=Array.isArray(_iterator3),_i3=0,_iterator3=_isArray3?_iterator3:_iterator3[Symbol.iterator]();;) {var _ref3;if(_isArray3){if(_i3 >= _iterator3.length)break;_ref3 = _iterator3[_i3++];}else {_i3 = _iterator3.next();if(_i3.done)break;_ref3 = _i3.value;}var channel=_ref3;self.channels.remove(channel);}self.servers.remove(server);client.emit("serverDeleted",server);}else {client.emit("warn","server was deleted but it was not in the cache");}break;case PacketType.SERVER_UPDATE:var server=self.servers.get("id",data.id);if(server){ // server exists
data.members = data.members || [];data.channels = data.channels || [];var newserver=new Server(data,self);newserver.members = server.members;newserver.memberMap = server.memberMap;newserver.channels = server.channels;if(newserver.equalsStrict(server)){ // already the same don't do anything
client.emit("debug","received server update but server already updated");}else {self.servers.update(server,newserver);client.emit("serverUpdated",server,newserver);}}else if(!server){client.emit("warn","server was updated but it was not in the cache");self.servers.add(new Server(data,self));client.emit("serverCreated",server);}break;case PacketType.CHANNEL_CREATE:var channel=self.channels.get("id",data.id);if(!channel){var server=self.servers.get("id",data.guild_id);if(server){if(data.is_private){client.emit("channelCreated",self.private_channels.add(new PMChannel(data,client)));}else {var chan=null;if(data.type === "text"){chan = self.channels.add(new TextChannel(data,client,server));}else {chan = self.channels.add(new VoiceChannel(data,client,server));}client.emit("channelCreated",server.channels.add(chan));}}else {client.emit("warn","channel created but server does not exist");}}else {client.emit("warn","channel created but already in cache");}break;case PacketType.CHANNEL_DELETE:var channel=self.channels.get("id",data.id);if(channel){if(channel.server) // accounts for PMs
channel.server.channels.remove(channel);self.channels.remove(channel);client.emit("channelDeleted",channel);}else {client.emit("warn","channel deleted but already out of cache?");}break;case PacketType.CHANNEL_UPDATE:var channel=self.channels.get("id",data.id) || self.private_channels.get("id",data.id);if(channel){if(channel instanceof PMChannel){ //PM CHANNEL
client.emit("channelUpdated",channel,self.private_channels.update(channel,new PMChannel(data,client)));}else {if(channel.server){if(channel.type === "text"){ //TEXT CHANNEL
var chan=new TextChannel(data,client,channel.server);chan.messages = channel.messages;channel.server.channels.update(channel,chan);self.channels.update(channel,chan);client.emit("channelUpdated",channel,chan);}else { //VOICE CHANNEL
var chan=new VoiceChannel(data,client,channel.server);channel.server.channels.update(channel,chan);self.channels.update(channel,chan);client.emit("channelUpdated",channel,chan);}}else {client.emit("warn","channel updated but server non-existant");}}}else {client.emit("warn","channel updated but not in cache");}break;case PacketType.SERVER_ROLE_CREATE:var server=self.servers.get("id",data.guild_id);if(server){client.emit("serverRoleCreated",server.roles.add(new Role(data.role,server,client)),server);}else {client.emit("warn","server role made but server not in cache");}break;case PacketType.SERVER_ROLE_DELETE:var server=self.servers.get("id",data.guild_id);if(server){var role=server.roles.get("id",data.role_id);if(role){server.roles.remove(role);client.emit("serverRoleDeleted",role);}else {client.emit("warn","server role deleted but role not in cache");}}else {client.emit("warn","server role deleted but server not in cache");}break;case PacketType.SERVER_ROLE_UPDATE:var server=self.servers.get("id",data.guild_id);if(server){var role=server.roles.get("id",data.role.id);if(role){var newRole=new Role(data.role,server,client);server.roles.update(role,newRole);client.emit("serverRoleUpdated",role,newRole);}else {client.emit("warn","server role updated but role not in cache");}}else {client.emit("warn","server role updated but server not in cache");}break;case PacketType.SERVER_MEMBER_ADD:var server=self.servers.get("id",data.guild_id);if(server){server.memberMap[data.user.id] = {roles:data.roles.map(function(pid){return server.roles.get("id",pid);}),mute:false,deaf:false,joinedAt:Date.parse(data.joined_at)};client.emit("serverNewMember",server,server.members.add(self.users.add(new User(data.user,client))));}else {client.emit("warn","server member added but server doesn't exist in cache");}break;case PacketType.SERVER_MEMBER_REMOVE:var server=self.servers.get("id",data.guild_id);if(server){var user=self.users.get("id",data.user.id);if(user){server.memberMap[data.user.id] = null;server.members.remove(user);client.emit("serverMemberRemoved",server,user);}else {client.emit("warn","server member removed but user doesn't exist in cache");}}else {client.emit("warn","server member removed but server doesn't exist in cache");}break;case PacketType.SERVER_MEMBER_UPDATE:var server=self.servers.get("id",data.guild_id);if(server){var user=self.users.get("id",data.user.id);if(user){server.memberMap[data.user.id].roles = data.roles.map(function(pid){return server.roles.get("id",pid);});server.memberMap[data.user.id].mute = data.mute;server.memberMap[data.user.id].deaf = data.deaf;client.emit("serverMemberUpdated",server,user);}else {client.emit("warn","server member removed but user doesn't exist in cache");}}else {client.emit("warn","server member updated but server doesn't exist in cache");}break;case PacketType.PRESENCE_UPDATE:var user=self.users.get("id",data.user.id);if(user){data.user.username = data.user.username || user.username;data.user.id = data.user.id || user.id;data.user.avatar = data.user.avatar || user.avatar;data.user.discriminator = data.user.discriminator || user.discriminator;var presenceUser=new User(data.user,client);if(presenceUser.equalsStrict(user)){ // a real presence update
client.emit("presence",user,data.status,data.game_id);user.status = data.status;user.gameID = data.game_id;}else { // a name change or avatar change
client.emit("userUpdate",user,presenceUser);self.users.update(user,presenceUser);}}else {client.emit("warn","presence update but user not in cache");}break;case PacketType.TYPING:var user=self.users.get("id",data.user_id);var channel=self.channels.get("id",data.channel_id) || self.private_channels.get("id",data.channel_id);if(user && channel){if(user.typing.since){user.typing.since = Date.now();user.typing.channel = channel;}else {user.typing.since = Date.now();user.typing.channel = channel;client.emit("userTypingStart",user,channel);}setTimeout(function(){if(Date.now() - user.typing.since > 5500){ // they haven't typed since
user.typing.since = null;user.typing.channel = null;client.emit("userTypingStop",user,channel);}},6000);}else {client.emit("warn","user typing but user or channel not existant in cache");}break;case PacketType.SERVER_BAN_ADD:var user=self.users.get("id",data.user.id);var server=self.servers.get("id",data.guild_id);if(user && server){client.emit("userBanned",user,server);}else {client.emit("warn","user banned but user/server not in cache.");}break;case PacketType.SERVER_BAN_REMOVE:var user=self.users.get("id",data.user.id);var server=self.servers.get("id",data.guild_id);if(user && server){client.emit("userUnbanned",user,server);}else {client.emit("warn","user unbanned but user/server not in cache.");}break;}};};_createClass(InternalClient,[{key:"uptime",get:function get(){return this.readyTime?Date.now() - this.readyTime:null;}}]);return InternalClient;})();module.exports = InternalClient;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var EventEmitter = require("events");
var request = require("superagent");
var WebSocket = require("ws");
var ConnectionState = require("./ConnectionState.js");
var Constants = require("../Constants.js"),
Endpoints = Constants.Endpoints,
PacketType = Constants.PacketType;
var Cache = require("../Util/Cache.js");
var Resolver = require("./Resolver/Resolver.js");
var User = require("../Structures/User.js"),
Channel = require("../Structures/Channel.js"),
TextChannel = require("../Structures/TextChannel.js"),
VoiceChannel = require("../Structures/VoiceChannel.js"),
PMChannel = require("../Structures/PMChannel.js"),
Server = require("../Structures/Server.js"),
Message = require("../Structures/Message.js"),
Role = require("../Structures/Role.js"),
Invite = require("../Structures/Invite.js"),
VoiceConnection = require("../Voice/VoiceConnection.js");
var zlib;
var InternalClient = (function () {
function InternalClient(discordClient) {
_classCallCheck(this, InternalClient);
this.client = discordClient;
this.state = ConnectionState.IDLE;
this.websocket = null;
if (this.client.options.compress) {
zlib = require("zlib");
}
// creates 4 caches with discriminators based on ID
this.users = new Cache();
this.channels = new Cache();
this.servers = new Cache();
this.private_channels = new Cache();
this.typingIntervals = [];
this.voiceConnection = null;
this.resolver = new Resolver(this);
this.readyTime = null;
}
//def leaveVoiceChannel
InternalClient.prototype.leaveVoiceChannel = function leaveVoiceChannel() {
var self = this;
return new Promise(function (resolve, reject) {
if (self.voiceConnection) {
self.voiceConnection.destroy();
self.voiceConnection = null;
resolve();
} else {
resolve();
}
});
};
//def joinVoiceChannel
InternalClient.prototype.joinVoiceChannel = function joinVoiceChannel(chann) {
var self = this;
return new Promise(function (resolve, reject) {
var channel = self.resolver.resolveVoiceChannel(chann);
if (channel) {
var next = function next() {
var session,
token,
server = channel.server,
endpoint;
var check = function check(m) {
var data = JSON.parse(m);
if (data.t === "VOICE_STATE_UPDATE") {
session = data.d.session_id;
} else if (data.t === "VOICE_SERVER_UPDATE") {
token = data.d.token;
endpoint = data.d.endpoint;
var chan = self.voiceConnection = new VoiceConnection(channel, self.client, session, token, server, endpoint);
chan.on("ready", function () {
return resolve(chan);
});
chan.on("error", reject);
self.client.emit("debug", "removed temporary voice websocket listeners");
self.websocket.removeListener("message", check);
}
};
self.websocket.on("message", check);
self.sendWS({
op: 4,
d: {
"guild_id": server.id,
"channel_id": channel.id,
"self_mute": false,
"self_deaf": false
}
});
};
self.leaveVoiceChannel().then(next);
} else {
reject(new Error("voice channel does not exist"));
}
});
};
// def createServer
InternalClient.prototype.createServer = function createServer(name) {
var region = arguments.length <= 1 || arguments[1] === undefined ? "london" : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
name = self.resolver.resolveString(name);
request.post(Endpoints.SERVERS).set("authorization", self.token).send({ name: name, region: region }).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
// valid server, wait until it is cached
var inter = setInterval(function () {
if (self.servers.get("id", res.body.id)) {
clearInterval(inter);
resolve(self.servers.get("id", res.body.id));
}
}, 20);
}
});
});
};
//def joinServer
InternalClient.prototype.joinServer = function joinServer(invite) {
var self = this;
return new Promise(function (resolve, reject) {
invite = self.resolver.resolveInviteID(invite);
if (invite) {
request.post(Endpoints.INVITE(invite)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
// valid server, wait until it is received via ws and cached
var inter = setInterval(function () {
if (self.servers.get("id", res.body.guild.id)) {
clearInterval(inter);
resolve(self.servers.get("id", res.body.guild.id));
}
}, 20);
}
});
} else {
reject(new Error("Not a valid invite"));
}
});
};
//def leaveServer
InternalClient.prototype.leaveServer = function leaveServer(srv) {
var self = this;
return new Promise(function (resolve, reject) {
var server = self.resolver.resolveServer(srv);
if (server) {
request.del(Endpoints.SERVER(server.id)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
// remove channels of server then the server
for (var _iterator = server.channels, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var chan = _ref;
self.channels.remove(chan);
}
// remove server
self.servers.remove(server);
resolve();
}
});
} else {
reject(new Error("server did not resolve"));
}
});
};
// def login
InternalClient.prototype.login = function login(email, password) {
var self = this;
var client = self.client;
return new Promise(function (resolve, reject) {
if (self.state === ConnectionState.DISCONNECTED || self.state === ConnectionState.IDLE) {
self.state = ConnectionState.LOGGING_IN;
request.post(Endpoints.LOGIN).send({ email: email, password: password }).end(function (err, res) {
if (err) {
self.state = ConnectionState.DISCONNECTED;
self.websocket = null;
client.emit("disconnected");
reject(new Error(err));
} else {
var token = res.body.token;
self.state = ConnectionState.LOGGED_IN;
self.token = token;
self.email = email;
self.password = password;
self.getGateway().then(function (url) {
self.createWS(url);
resolve(token);
})["catch"](function (e) {
self.state = ConnectionState.DISCONNECTED;
client.emit("disconnected");
reject(new Error(err));
});
}
});
} else {
reject(new Error("already logging in/logged in/ready!"));
}
});
};
// def logout
InternalClient.prototype.logout = function logout() {
var _this = this;
var self = this;
return new Promise(function (resolve, reject) {
if (self.state === ConnectionState.DISCONNECTED || self.state === ConnectionState.IDLE) {
reject(new Error("Client is not logged in!"));
return;
}
request.post(Endpoints.LOGOUT).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
if (_this.websocket) {
_this.websocket.close();
_this.websocket = null;
}
self.token = null;
self.email = null;
self.password = null;
self.state = ConnectionState.DISCONNECTED;
resolve();
}
});
});
};
// def startPM
InternalClient.prototype.startPM = function startPM(resUser) {
var self = this;
return new Promise(function (resolve, reject) {
var user = self.resolver.resolveUser(resUser);
if (user) {
// start the PM
request.post("" + Endpoints.USER_CHANNELS(user.id)).set("authorization", self.token).send({
recipient_id: user.id
}).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
resolve(self.private_channels.add(new PMChannel(res.body, self.client)));
}
});
} else {
reject(new Error("Unable to resolve resUser to a User"));
}
});
};
// def getGateway
InternalClient.prototype.getGateway = function getGateway() {
var self = this;
return new Promise(function (resolve, reject) {
request.get(Endpoints.GATEWAY).set("authorization", self.token).end(function (err, res) {
if (err) reject(err);else resolve(res.body.url);
});
});
};
// def sendMessage
InternalClient.prototype.sendMessage = function sendMessage(where, _content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(where).then(next)["catch"](function (e) {
return reject(new Error("Error resolving destination - " + e));
});
function next(destination) {
//var destination;
var content = self.resolver.resolveString(_content);
var mentions = self.resolver.resolveMentions(content);
request.post(Endpoints.CHANNEL_MESSAGES(destination.id)).set("authorization", self.token).send({
content: content,
mentions: mentions,
tts: options.tts
}).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
resolve(destination.messages.add(new Message(res.body, destination, self.client)));
}
});
}
});
};
// def deleteMessage
InternalClient.prototype.deleteMessage = function deleteMessage(_message) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
var message = self.resolver.resolveMessage(_message);
if (message) {
var deleteMsg = function deleteMsg() {
request.del(Endpoints.CHANNEL_MESSAGE(message.channel.id, message.id)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
message.channel.messages.remove(message);
resolve();
}
});
};
if (options.wait) {
setTimeout(deleteMsg, options.wait);
} else {
deleteMsg();
}
} else {
reject(new Error("Supplied message did not resolve to a message!"));
}
});
};
// def updateMessage
InternalClient.prototype.updateMessage = function updateMessage(msg, _content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
var message = self.resolver.resolveMessage(msg);
if (message) {
var content = self.resolver.resolveString(_content);
var mentions = self.resolver.resolveMentions(content);
request.patch(Endpoints.CHANNEL_MESSAGE(message.channel.id, message.id)).set("authorization", self.token).send({
content: content,
tts: options.tts,
mentions: mentions
}).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
resolve(message.channel.messages.update(message, new Message(res.body, message.channel, self.client)));
}
});
} else {
reject(new Error("Supplied message did not resolve to a message!"));
}
});
};
// def sendFile
InternalClient.prototype.sendFile = function sendFile(where, _file) {
var name = arguments.length <= 2 || arguments[2] === undefined ? "image.png" : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(where).then(next)["catch"](function (e) {
return reject(new Error("couldn't resolve to channel - " + e));
});
function next(channel) {
var file = self.resolver.resolveFile(_file);
request.post(Endpoints.CHANNEL_MESSAGES(channel.id)).set("authorization", self.token).attach("file", file, name).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
resolve(channel.messages.add(new Message(res.body, channel, self.client)));
}
});
}
});
};
// def getChannelLogs
InternalClient.prototype.getChannelLogs = function getChannelLogs(_channel) {
var limit = arguments.length <= 1 || arguments[1] === undefined ? 500 : arguments[1];
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(_channel).then(next)["catch"](function (e) {
return reject(new Error("couldn't resolve to channel - " + e));
});
function next(channel) {
if (options.before) options.before = self.resolver.resolveMessage(options.before);
if (options.after) options.after = self.resolver.resolveMessage(options.after);
var params = [];
if (options.before) params.push("before=" + options.before.id);
if (options.after) params.push("after=" + options.after.id);
var joinedParams = params.join();
if (joinedParams !== "") joinedParams = "&" + params.join();
request.get(Endpoints.CHANNEL_MESSAGES(channel.id) + "?limit=" + limit + joinedParams).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
var logs = [];
res.body.forEach(function (msg) {
logs.push(channel.messages.add(new Message(msg, channel, self.client)));
});
resolve(logs);
}
});
}
});
};
// def getBans
InternalClient.prototype.getBans = function getBans(server) {
var self = this;
return new Promise(function (resolve, reject) {
server = self.resolver.resolveServer(server);
request.get("" + Endpoints.SERVER_BANS(server.id)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(new Error(err));
} else {
var bans = [];
res.body.forEach(function (ban) {
bans.push(self.users.add(new User(ban.user, self.client)));
});
resolve(bans);
}
});
});
};
// def createChannel
InternalClient.prototype.createChannel = function createChannel(server, name) {
var type = arguments.length <= 2 || arguments[2] === undefined ? "text" : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
server = self.resolver.resolveServer(server);
request.post(Endpoints.SERVER_CHANNELS(server.id)).set("authorization", self.token).send({
name: name, type: type
}).end(function (err, res) {
if (err) {
reject(err);
} else {
var channel;
if (res.body.type === "text") {
channel = new TextChannel(res.body, self.client, server);
} else {
channel = new VoiceChannel(res.body, self.client, server);
}
resolve(server.channels.add(self.channels.add(channel)));
}
});
});
};
// def deleteChannel
InternalClient.prototype.deleteChannel = function deleteChannel(_channel) {
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(_channel).then(next)["catch"](reject);
function next(channel) {
request.del(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
channel.server.channels.remove(channel);
self.channels.remove(channel);
resolve();
}
});
}
});
};
// def banMember
InternalClient.prototype.banMember = function banMember(user, server) {
var length = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
user = self.resolver.resolveUser(user);
server = self.resolver.resolveServer(server);
request.put(Endpoints.SERVER_BANS(server.id) + "/" + user.id + "/?delete-message-days=" + length).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
// def unbanMember
InternalClient.prototype.unbanMember = function unbanMember(user, server) {
var self = this;
return new Promise(function (resolve, reject) {
server = self.resolver.resolveServer(server);
user = self.resolver.resolveUser(user);
request.del(Endpoints.SERVER_BANS(server.id) + "/" + user.id).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
// def kickMember
InternalClient.prototype.kickMember = function kickMember(user, server) {
var self = this;
return new Promise(function (resolve, reject) {
user = self.resolver.resolveUser(user);
server = self.resolver.resolveServer(server);
request.del(Endpoints.SERVER_MEMBERS(server.id) + "/" + user.id).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
// def createRole
InternalClient.prototype.createRole = function createRole(server, data) {
var self = this;
return new Promise(function (resolve, reject) {
server = self.resolver.resolveServer(server);
request.post(Endpoints.SERVER_ROLES(server.id)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
var role = server.roles.add(new Role(res.body, server, self.client));
if (data) {
self.updateRole(role, data).then(resolve)["catch"](reject);
} else {
resolve(role);
}
}
});
});
};
// def updateRole
InternalClient.prototype.updateRole = function updateRole(role, data) {
var self = this;
data = data || {};
data.permissions = data.permissions || [];
return new Promise(function (resolve, reject) {
var server = self.resolver.resolveServer(role.server);
var permissions = 0;
for (var _iterator2 = data.permissions, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var perm = _ref2;
if (perm instanceof String || typeof perm === "string") {
permissions |= Constants.Permissions[perm] || 0;
} else {
permissions |= perm;
}
}
data.color = data.color || 0;
request.patch(Endpoints.SERVER_ROLES(server.id) + "/" + role.id).set("authorization", self.token).send({
color: data.color || role.color,
hoist: data.hoist || role.hoist,
name: data.name || role.name,
permissions: permissions
}).end(function (err, res) {
if (err) {
reject(err);
} else {
var nrole = new Role(res.body, server, self.client);
resolve(server.roles.update(role, nrole));
}
});
});
};
// def deleteRole
InternalClient.prototype.deleteRole = function deleteRole(role) {
var self = this;
return new Promise(function (resolve, reject) {
request.del(Endpoints.SERVER_ROLES(role.server.id) + "/" + role.id).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve();
// the ws cache will handle it
// role.server.roles.remove(role);
}
});
});
};
//def addMemberToRole
InternalClient.prototype.addMemberToRole = function addMemberToRole(member, role) {
var self = this;
return new Promise(function (resolve, reject) {
member = self.resolver.resolveUser(member);
if (!member || !role) {
reject(new Error("member/role not in server"));
return;
}
if (role.server.memberMap[member.id]) {
var roleIDS = role.server.memberMap[member.id].roles.map(function (r) {
return r.id;
}).concat(role.id);
request.patch(Endpoints.SERVER_MEMBERS(role.server.id) + "/" + member.id).set("authorization", self.token).send({
roles: roleIDS
}).end(function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
reject(new Error("member not in server"));
}
});
};
//def removeMemberFromRole
InternalClient.prototype.removeMemberFromRole = function removeMemberFromRole(member, role) {
var self = this;
return new Promise(function (resolve, reject) {
member = self.resolver.resolveUser(member);
if (!member || !role) {
reject(new Error("member/role not in server"));
return;
}
if (role.server.memberMap[member.id]) {
var roleIDS = role.server.memberMap[member.id].roles.map(function (r) {
return r.id;
});
for (var item in roleIDS) {
if (roleIDS[item] === role.id) {
roleIDS.splice(item, 1);
}
}
request.patch(Endpoints.SERVER_MEMBERS(role.server.id) + "/" + member.id).set("authorization", self.token).send({
roles: roleIDS
}).end(function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
reject(new Error("member not in server"));
}
});
};
// def createInvite
InternalClient.prototype.createInvite = function createInvite(chanServ, options) {
var self = this;
return new Promise(function (resolve, reject) {
if (chanServ instanceof Channel) {
// do something
} else if (chanServ instanceof Server) {
// do something
} else {
chanServ = self.resolver.resolveServer(chanServ) || self.resolver.resolveChannel(chanServ);
}
if (!chanServ) {
reject(new Error("couldn't resolve where"));
return;
}
if (!options) {
options = { validate: null };
} else {
options.max_age = options.maxAge || 0;
options.max_uses = options.maxUses || 0;
options.temporary = options.temporary || false;
options.xkcdpass = options.xkcd || false;
}
var epoint;
if (chanServ instanceof Channel) {
epoint = Endpoints.CHANNEL_INVITES(chanServ.id);
} else {
epoint = Endpoints.SERVER_INVITES(chanServ.id);
}
request.post(epoint).set("authorization", self.token).send(options).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve(new Invite(res.body, self.channels.get("id", res.body.channel.id), self.client));
}
});
});
};
//def deleteInvite
InternalClient.prototype.deleteInvite = function deleteInvite(invite) {
var self = this;
return new Promise(function (resolve, reject) {
invite = self.resolver.resolveInviteID(invite);
if (invite) {
request.del(Endpoints.INVITE(invite)).set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
reject(new Error("Not a valid invite"));
}
});
};
//def overwritePermissions
InternalClient.prototype.overwritePermissions = function overwritePermissions(channel, role, updated) {
var self = this;
return new Promise(function (resolve, reject) {
channel = self.resolver.resolveChannel(channel)["catch"](reject).then(next);
function next(channel) {
var user;
if (role instanceof User) {
user = role;
}
var data = {};
data.allow = 0;
data.deny = 0;
updated.allow = updated.allow || [];
updated.deny = updated.deny || [];
if (role instanceof Role) {
data.id = role.id;
data.type = "role";
} else if (user) {
data.id = user.id;
data.type = "member";
} else {
reject(new Error("role incorrect"));
return;
}
for (var perm in updated) {
if (updated[perm]) {
if (perm instanceof String || typeof perm === "string") {
data.allow |= Constants.Permissions[perm] || 0;
} else {
data.allow |= perm;
}
} else {
if (perm instanceof String || typeof perm === "string") {
data.deny |= Constants.Permissions[perm] || 0;
} else {
data.deny |= perm;
}
}
}
request.put(Endpoints.CHANNEL_PERMISSIONS(channel.id) + "/" + data.id).set("authorization", self.token).send(data).end(function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
}
});
};
//def setStatus
InternalClient.prototype.setStatus = function setStatus(idleStatus, gameID) {
var self = this;
self.idleStatus = idleStatus || self.idleStatus || null;
if (idleStatus) {
if (idleStatus == "online" || idleStatus == "here" || idleStatus == "available") {
self.idleStatus = null;
}
}
self.gameID = self.resolver.resolveGameID(gameID) || self.gameID || null;
return new Promise(function (resolve, reject) {
var packet = {
op: 3,
d: {
idle_since: self.idleStatus,
game_id: self.gameID
}
};
if (self.idleStatus == "idle" || self.idleStatus == "away") {
packet.d.idle_since = Date.now();
}
self.sendWS(packet);
resolve();
});
};
//def sendTyping
InternalClient.prototype.sendTyping = function sendTyping(channel) {
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(channel).then(next)["catch"](reject);
function next(channel) {
request.post(Endpoints.CHANNEL(channel.id) + "/typing").set("authorization", self.token).end(function (err, res) {
if (err) {
reject(err);
} else {
resolve();
}
});
}
});
};
//def startTyping
InternalClient.prototype.startTyping = function startTyping(channel) {
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(channel).then(next)["catch"](reject);
function next(channel) {
if (self.typingIntervals[channel.id]) {
// typing interval already exists, leave it alone
reject(new Error("Already typing in that channel"));
return;
}
self.sendTyping(channel);
self.typingIntervals[channel.id] = setInterval(function () {
return self.sendTyping(channel);
}, 4000);
}
});
};
//def stopTyping
InternalClient.prototype.stopTyping = function stopTyping(channel) {
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(channel).then(next)["catch"](reject);
function next(channel) {
if (!self.typingIntervals[channel.id]) {
// typing interval doesn't exist
reject(new Error("Not typing in that channel"));
return;
}
clearInterval(self.typingIntervals[channel.id]);
self.typingIntervals[channel.id] = false;
}
});
};
//def updateDetails
InternalClient.prototype.updateDetails = function updateDetails(data) {
var self = this;
return new Promise(function (resolve, reject) {
request.patch(Endpoints.ME).set("authorization", self.token).send({
avatar: self.resolver.resolveToBase64(data.avatar) || self.user.avatar,
email: data.email || self.email,
new_password: data.newPassword || null,
password: data.password || self.password,
username: data.username || self.user.username
}).end(function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
//def setAvatar
InternalClient.prototype.setAvatar = function setAvatar(avatar) {
return this.updateDetails({ avatar: avatar });
};
//def setUsername
InternalClient.prototype.setUsername = function setUsername(username) {
return this.updateDetails({ username: username });
};
//def setTopic
InternalClient.prototype.setTopic = function setTopic(chann) {
var topic = arguments.length <= 1 || arguments[1] === undefined ? "" : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(chann).then(next)["catch"](reject);
function next(channel) {
request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({
name: channel.name,
position: channel.position,
topic: topic
}).end(function (err, res) {
if (err) {
reject(err);
} else {
channel.topic = res.body.topic;
resolve();
}
});
}
});
};
//def setChannelName
InternalClient.prototype.setChannelName = function setChannelName(chann) {
var name = arguments.length <= 1 || arguments[1] === undefined ? "discordjs_is_the_best" : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(chann).then(next)["catch"](reject);
function next(channel) {
request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({
name: name,
position: channel.position,
topic: channel.topic
}).end(function (err, res) {
if (err) {
reject(err);
} else {
channel.name = res.body.name;
resolve();
}
});
}
});
};
//def setChannelNameAndTopic
InternalClient.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(chann) {
var name = arguments.length <= 1 || arguments[1] === undefined ? "discordjs_is_the_best" : arguments[1];
var topic = arguments.length <= 2 || arguments[2] === undefined ? "" : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.resolver.resolveChannel(chann).then(next)["catch"](reject);
function next(channel) {
request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({
name: name,
position: channel.position,
topic: topic
}).end(function (err, res) {
if (err) {
reject(err);
} else {
channel.name = res.body.name;
channel.topic = res.body.topic;
resolve();
}
});
}
});
};
//def updateChannel
InternalClient.prototype.updateChannel = function updateChannel(chann, data) {
return this.setChannelNameAndTopic(chann, data.name, data.topic);
};
//def ack
InternalClient.prototype.ack = function ack(msg) {
var self = this;
return new Promise(function (resolve, reject) {
msg = self.resolver.resolveMessage(msg);
if (msg) {
request.post(Endpoints.CHANNEL_MESSAGE(msg.channel.id, msg.id) + "/ack").set("authorization", self.token).end(function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
reject(new Error("Message does not exist"));
}
});
};
InternalClient.prototype.sendWS = function sendWS(object) {
if (this.websocket) this.websocket.send(JSON.stringify(object));
};
InternalClient.prototype.createWS = function createWS(url) {
var self = this;
var client = self.client;
if (this.websocket) return false;
this.websocket = new WebSocket(url);
this.websocket.onopen = function () {
self.sendWS({
op: 2,
d: {
token: self.token,
v: 3,
compress: self.client.options.compress,
properties: {
"$os": "discord.js",
"$browser": "discord.js",
"$device": "discord.js",
"$referrer": "discord.js",
"$referring_domain": "discord.js"
}
}
});
};
this.websocket.onclose = function () {
self.websocket = null;
self.state = ConnectionState.DISCONNECTED;
client.emit("disconnected");
};
this.websocket.onerror = function (e) {
client.emit("error", e);
};
this.websocket.onmessage = function (e) {
if (e.type === "Binary") {
if (!zlib) zlib = require("zlib");
e.data = zlib.inflateSync(e.data).toString();
}
var packet, data;
try {
packet = JSON.parse(e.data);
data = packet.d;
} catch (e) {
client.emit("error", e);
return;
}
client.emit("raw", packet);
switch (packet.t) {
case PacketType.READY:
var startTime = Date.now();
self.user = self.users.add(new User(data.user, client));
data.guilds.forEach(function (server) {
self.servers.add(new Server(server, client));
});
data.private_channels.forEach(function (pm) {
self.private_channels.add(new PMChannel(pm, client));
});
self.state = ConnectionState.READY;
setInterval(function () {
return self.sendWS({ op: 1, d: Date.now() });
}, data.heartbeat_interval);
client.emit("ready");
client.emit("debug", "ready packet took " + (Date.now() - startTime) + "ms to process");
client.emit("debug", "ready with " + self.servers.length + " servers, " + self.channels.length + " channels and " + self.users.length + " users cached.");
self.readyTime = Date.now();
break;
case PacketType.MESSAGE_CREATE:
// format: https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-format
var channel = self.channels.get("id", data.channel_id) || self.private_channels.get("id", data.channel_id);
if (channel) {
var msg = channel.messages.add(new Message(data, channel, client));
client.emit("message", msg);
self.ack(msg);
} else {
client.emit("warn", "message created but channel is not cached");
}
break;
case PacketType.MESSAGE_DELETE:
// format https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-delete
var channel = self.channels.get("id", data.channel_id) || self.private_channels.get("id", data.channel_id);
if (channel) {
// potentially blank
var msg = channel.messages.get("id", data.id);
client.emit("messageDeleted", msg);
if (msg) {
channel.messages.remove(msg);
}
} else {
client.emit("warn", "message was deleted but channel is not cached");
}
break;
case PacketType.MESSAGE_UPDATE:
// format https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-format
var channel = self.channels.get("id", data.channel_id) || self.private_channels.get("id", data.channel_id);
if (channel) {
// potentially blank
var msg = channel.messages.get("id", data.id);
if (msg) {
// old message exists
data.nonce = data.nonce || msg.nonce;
data.attachments = data.attachments || msg.attachments;
data.tts = data.tts || msg.tts;
data.embeds = data.embeds || msg.embeds;
data.timestamp = data.timestamp || msg.timestamp;
data.mention_everyone = data.mention_everyone || msg.everyoneMentioned;
data.content = data.content || msg.content;
data.mentions = data.mentions || msg.mentions;
data.author = data.author || msg.author;
var nmsg = channel.messages.update(msg, new Message(data, channel, client));
client.emit("messageUpdated", nmsg, msg);
}
} else {
client.emit("warn", "message was updated but channel is not cached");
}
break;
case PacketType.SERVER_CREATE:
var server = self.servers.get("id", data.id);
if (!server) {
self.servers.add(new Server(data, client));
client.emit("serverCreated", server);
}
break;
case PacketType.SERVER_DELETE:
var server = self.servers.get("id", data.id);
if (server) {
for (var _iterator3 = server.channels, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var channel = _ref3;
self.channels.remove(channel);
}
self.servers.remove(server);
client.emit("serverDeleted", server);
} else {
client.emit("warn", "server was deleted but it was not in the cache");
}
break;
case PacketType.SERVER_UPDATE:
var server = self.servers.get("id", data.id);
if (server) {
// server exists
data.members = data.members || [];
data.channels = data.channels || [];
var newserver = new Server(data, self);
newserver.members = server.members;
newserver.memberMap = server.memberMap;
newserver.channels = server.channels;
if (newserver.equalsStrict(server)) {
// already the same don't do anything
client.emit("debug", "received server update but server already updated");
} else {
self.servers.update(server, newserver);
client.emit("serverUpdated", server, newserver);
}
} else if (!server) {
client.emit("warn", "server was updated but it was not in the cache");
self.servers.add(new Server(data, self));
client.emit("serverCreated", server);
}
break;
case PacketType.CHANNEL_CREATE:
var channel = self.channels.get("id", data.id);
if (!channel) {
var server = self.servers.get("id", data.guild_id);
if (server) {
if (data.is_private) {
client.emit("channelCreated", self.private_channels.add(new PMChannel(data, client)));
} else {
var chan = null;
if (data.type === "text") {
chan = self.channels.add(new TextChannel(data, client, server));
} else {
chan = self.channels.add(new VoiceChannel(data, client, server));
}
client.emit("channelCreated", server.channels.add(chan));
}
} else {
client.emit("warn", "channel created but server does not exist");
}
} else {
client.emit("warn", "channel created but already in cache");
}
break;
case PacketType.CHANNEL_DELETE:
var channel = self.channels.get("id", data.id);
if (channel) {
if (channel.server) // accounts for PMs
channel.server.channels.remove(channel);
self.channels.remove(channel);
client.emit("channelDeleted", channel);
} else {
client.emit("warn", "channel deleted but already out of cache?");
}
break;
case PacketType.CHANNEL_UPDATE:
var channel = self.channels.get("id", data.id) || self.private_channels.get("id", data.id);
if (channel) {
if (channel instanceof PMChannel) {
//PM CHANNEL
client.emit("channelUpdated", channel, self.private_channels.update(channel, new PMChannel(data, client)));
} else {
if (channel.server) {
if (channel.type === "text") {
//TEXT CHANNEL
var chan = new TextChannel(data, client, channel.server);
chan.messages = channel.messages;
channel.server.channels.update(channel, chan);
self.channels.update(channel, chan);
client.emit("channelUpdated", channel, chan);
} else {
//VOICE CHANNEL
var chan = new VoiceChannel(data, client, channel.server);
channel.server.channels.update(channel, chan);
self.channels.update(channel, chan);
client.emit("channelUpdated", channel, chan);
}
} else {
client.emit("warn", "channel updated but server non-existant");
}
}
} else {
client.emit("warn", "channel updated but not in cache");
}
break;
case PacketType.SERVER_ROLE_CREATE:
var server = self.servers.get("id", data.guild_id);
if (server) {
client.emit("serverRoleCreated", server.roles.add(new Role(data.role, server, client)), server);
} else {
client.emit("warn", "server role made but server not in cache");
}
break;
case PacketType.SERVER_ROLE_DELETE:
var server = self.servers.get("id", data.guild_id);
if (server) {
var role = server.roles.get("id", data.role_id);
if (role) {
server.roles.remove(role);
client.emit("serverRoleDeleted", role);
} else {
client.emit("warn", "server role deleted but role not in cache");
}
} else {
client.emit("warn", "server role deleted but server not in cache");
}
break;
case PacketType.SERVER_ROLE_UPDATE:
var server = self.servers.get("id", data.guild_id);
if (server) {
var role = server.roles.get("id", data.role.id);
if (role) {
var newRole = new Role(data.role, server, client);
server.roles.update(role, newRole);
client.emit("serverRoleUpdated", role, newRole);
} else {
client.emit("warn", "server role updated but role not in cache");
}
} else {
client.emit("warn", "server role updated but server not in cache");
}
break;
case PacketType.SERVER_MEMBER_ADD:
var server = self.servers.get("id", data.guild_id);
if (server) {
server.memberMap[data.user.id] = {
roles: data.roles.map(function (pid) {
return server.roles.get("id", pid);
}),
mute: false,
deaf: false,
joinedAt: Date.parse(data.joined_at)
};
client.emit("serverNewMember", server, server.members.add(self.users.add(new User(data.user, client))));
} else {
client.emit("warn", "server member added but server doesn't exist in cache");
}
break;
case PacketType.SERVER_MEMBER_REMOVE:
var server = self.servers.get("id", data.guild_id);
if (server) {
var user = self.users.get("id", data.user.id);
if (user) {
server.memberMap[data.user.id] = null;
server.members.remove(user);
client.emit("serverMemberRemoved", server, user);
} else {
client.emit("warn", "server member removed but user doesn't exist in cache");
}
} else {
client.emit("warn", "server member removed but server doesn't exist in cache");
}
break;
case PacketType.SERVER_MEMBER_UPDATE:
var server = self.servers.get("id", data.guild_id);
if (server) {
var user = self.users.get("id", data.user.id);
if (user) {
server.memberMap[data.user.id].roles = data.roles.map(function (pid) {
return server.roles.get("id", pid);
});
server.memberMap[data.user.id].mute = data.mute;
server.memberMap[data.user.id].deaf = data.deaf;
client.emit("serverMemberUpdated", server, user);
} else {
client.emit("warn", "server member removed but user doesn't exist in cache");
}
} else {
client.emit("warn", "server member updated but server doesn't exist in cache");
}
break;
case PacketType.PRESENCE_UPDATE:
var user = self.users.get("id", data.user.id);
if (user) {
data.user.username = data.user.username || user.username;
data.user.id = data.user.id || user.id;
data.user.avatar = data.user.avatar || user.avatar;
data.user.discriminator = data.user.discriminator || user.discriminator;
var presenceUser = new User(data.user, client);
if (presenceUser.equalsStrict(user)) {
// a real presence update
client.emit("presence", user, data.status, data.game_id);
user.status = data.status;
user.gameID = data.game_id;
} else {
// a name change or avatar change
client.emit("userUpdate", user, presenceUser);
self.users.update(user, presenceUser);
}
} else {
client.emit("warn", "presence update but user not in cache");
}
break;
case PacketType.TYPING:
var user = self.users.get("id", data.user_id);
var channel = self.channels.get("id", data.channel_id) || self.private_channels.get("id", data.channel_id);
if (user && channel) {
if (user.typing.since) {
user.typing.since = Date.now();
user.typing.channel = channel;
} else {
user.typing.since = Date.now();
user.typing.channel = channel;
client.emit("userTypingStart", user, channel);
}
setTimeout(function () {
if (Date.now() - user.typing.since > 5500) {
// they haven't typed since
user.typing.since = null;
user.typing.channel = null;
client.emit("userTypingStop", user, channel);
}
}, 6000);
} else {
client.emit("warn", "user typing but user or channel not existant in cache");
}
break;
case PacketType.SERVER_BAN_ADD:
var user = self.users.get("id", data.user.id);
var server = self.servers.get("id", data.guild_id);
if (user && server) {
client.emit("userBanned", user, server);
} else {
client.emit("warn", "user banned but user/server not in cache.");
}
break;
case PacketType.SERVER_BAN_REMOVE:
var user = self.users.get("id", data.user.id);
var server = self.servers.get("id", data.guild_id);
if (user && server) {
client.emit("userUnbanned", user, server);
} else {
client.emit("warn", "user unbanned but user/server not in cache.");
}
break;
}
};
};
_createClass(InternalClient, [{
key: "uptime",
get: function get() {
return this.readyTime ? Date.now() - this.readyTime : null;
}
}]);
return InternalClient;
})();
module.exports = InternalClient;

@@ -1,13 +0,239 @@

"use strict"; /* global Buffer */function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var fs=require("fs");var User=require("../../Structures/User.js"),Channel=require("../../Structures/Channel.js"),TextChannel=require("../../Structures/TextChannel.js"),VoiceChannel=require("../../Structures/VoiceChannel.js"),ServerChannel=require("../../Structures/ServerChannel.js"),PMChannel=require("../../Structures/PMChannel.js"),Server=require("../../Structures/Server.js"),Message=require("../../Structures/Message.js"),Invite=require("../../Structures/Invite.js");var Resolver=(function(){function Resolver(internal){_classCallCheck(this,Resolver);this.internal = internal;}Resolver.prototype.resolveToBase64 = function resolveToBase64(resource){if(resource instanceof Buffer){resource = resource.toString("base64");resource = "data:image/jpg;base64," + resource;}return resource;};Resolver.prototype.resolveInviteID = function resolveInviteID(resource){if(resource instanceof Invite){return resource.id;}else if(typeof resource == "string" || resource instanceof String){if(resource.indexOf("http") === 0){var split=resource.split("/");return split.pop();}else {return resource;}}return null;};Resolver.prototype.resolveServer = function resolveServer(resource){if(resource instanceof Server){return resource;}else if(resource instanceof ServerChannel){return resource.server;}else if(resource instanceof String || typeof resource === "string"){return this.internal.servers.get("id",resource);}else if(resource instanceof Message){if(resource.channel instanceof TextChannel){return resource.server;}}return null;};Resolver.prototype.resolveFile = function resolveFile(resource){if(typeof resource === "string" || resource instanceof String){return fs.createReadStream(resource);}else {return resource;}};Resolver.prototype.resolveMentions = function resolveMentions(resource){ // resource is a string
var _mentions=[];for(var _iterator=resource.match(/<@[^>]*>/g) || [],_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var mention=_ref;_mentions.push(mention.substring(2,mention.length - 1));}return _mentions;};Resolver.prototype.resolveString = function resolveString(resource){ // accepts Array, Channel, Server, User, Message, String and anything
// toString()-able
var final=resource;if(resource instanceof Array){final = resource.join("\n");}return final.toString();};Resolver.prototype.resolveUser = function resolveUser(resource){ /*
accepts a Message, Channel, Server, String ID, User, PMChannel
*/var found=null;if(resource instanceof User){found = resource;}else if(resource instanceof Message){found = resource.author;}else if(resource instanceof TextChannel){var lmsg=resource.lastMessage;if(lmsg){found = lmsg.author;}}else if(resource instanceof Server){found = resource.owner;}else if(resource instanceof PMChannel){found = resource.recipient;}else if(resource instanceof String || typeof resource === "string"){found = this.client.internal.users.get("id",resource);}return found;};Resolver.prototype.resolveMessage = function resolveMessage(resource){ // accepts a Message, PMChannel & TextChannel
var found=null;if(resource instanceof TextChannel || resource instanceof PMChannel){found = resource.lastMessage;}else if(resource instanceof Message){found = resource;}return found;};Resolver.prototype.resolveVoiceChannel = function resolveVoiceChannel(resource){ // resolveChannel will also work but this is more apt
if(resource instanceof VoiceChannel){return resource;}return null;};Resolver.prototype.resolveChannel = function resolveChannel(resource){ /*
accepts a Message, Channel, Server, String ID, User
*/var self=this;return new Promise(function(resolve,reject){var found=null;if(resource instanceof Message){found = resource.channel;}else if(resource instanceof Channel){found = resource;}else if(resource instanceof Server){found = resource.channels.get("id",resource.id);}else if(resource instanceof String || typeof resource === "string"){found = self.internal.channels.get("id",resource);}else if(resource instanceof User){ // see if a PM exists
var chatFound=false;for(var _iterator2=self.internal.private_channels,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var pmchat=_ref2;if(pmchat.recipient.equals(resource)){chatFound = pmchat;break;}}if(chatFound){ // a PM already exists!
found = chatFound;}else { // PM does not exist :\
self.internal.startPM(resource).then(function(pmchannel){return resolve(pmchannel);})["catch"](function(e){return reject(e);});return;}}if(found)resolve(found);else reject(new Error("Didn't found anything"));});};return Resolver;})();module.exports = Resolver;
"use strict";
/* global Buffer */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var fs = require("fs");
var User = require("../../Structures/User.js"),
Channel = require("../../Structures/Channel.js"),
TextChannel = require("../../Structures/TextChannel.js"),
VoiceChannel = require("../../Structures/VoiceChannel.js"),
ServerChannel = require("../../Structures/ServerChannel.js"),
PMChannel = require("../../Structures/PMChannel.js"),
Server = require("../../Structures/Server.js"),
Message = require("../../Structures/Message.js"),
Invite = require("../../Structures/Invite.js"),
Games = require("../../../ref/gameMap.js");
var Resolver = (function () {
function Resolver(internal) {
_classCallCheck(this, Resolver);
this.internal = internal;
}
Resolver.prototype.resolveGameID = function resolveGameID(resource) {
if (!isNaN(resource) && parseInt(resource) % 1 === 0) {
return resource;
} else if (typeof resource == "string" || resource instanceof String) {
for (var _iterator = Games, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var game = _ref;
if (game.name.toUpperCase() === resource.toUpperCase()) {
return game.id;
}
}
}
return null;
};
Resolver.prototype.resolveToBase64 = function resolveToBase64(resource) {
if (resource instanceof Buffer) {
resource = resource.toString("base64");
resource = "data:image/jpg;base64," + resource;
}
return resource;
};
Resolver.prototype.resolveInviteID = function resolveInviteID(resource) {
if (resource instanceof Invite) {
return resource.id;
} else if (typeof resource == "string" || resource instanceof String) {
if (resource.indexOf("http") === 0) {
var split = resource.split("/");
return split.pop();
} else {
return resource;
}
}
return null;
};
Resolver.prototype.resolveServer = function resolveServer(resource) {
if (resource instanceof Server) {
return resource;
} else if (resource instanceof ServerChannel) {
return resource.server;
} else if (resource instanceof String || typeof resource === "string") {
return this.internal.servers.get("id", resource);
} else if (resource instanceof Message) {
if (resource.channel instanceof TextChannel) {
return resource.server;
}
}
return null;
};
Resolver.prototype.resolveFile = function resolveFile(resource) {
if (typeof resource === "string" || resource instanceof String) {
return fs.createReadStream(resource);
} else {
return resource;
}
};
Resolver.prototype.resolveMentions = function resolveMentions(resource) {
// resource is a string
var _mentions = [];
for (var _iterator2 = resource.match(/<@[^>]*>/g) || [], _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var mention = _ref2;
_mentions.push(mention.substring(2, mention.length - 1));
}
return _mentions;
};
Resolver.prototype.resolveString = function resolveString(resource) {
// accepts Array, Channel, Server, User, Message, String and anything
// toString()-able
var final = resource;
if (resource instanceof Array) {
final = resource.join("\n");
}
return final.toString();
};
Resolver.prototype.resolveUser = function resolveUser(resource) {
/*
accepts a Message, Channel, Server, String ID, User, PMChannel
*/
var found = null;
if (resource instanceof User) {
found = resource;
} else if (resource instanceof Message) {
found = resource.author;
} else if (resource instanceof TextChannel) {
var lmsg = resource.lastMessage;
if (lmsg) {
found = lmsg.author;
}
} else if (resource instanceof Server) {
found = resource.owner;
} else if (resource instanceof PMChannel) {
found = resource.recipient;
} else if (resource instanceof String || typeof resource === "string") {
found = this.client.internal.users.get("id", resource);
}
return found;
};
Resolver.prototype.resolveMessage = function resolveMessage(resource) {
// accepts a Message, PMChannel & TextChannel
var found = null;
if (resource instanceof TextChannel || resource instanceof PMChannel) {
found = resource.lastMessage;
} else if (resource instanceof Message) {
found = resource;
}
return found;
};
Resolver.prototype.resolveVoiceChannel = function resolveVoiceChannel(resource) {
// resolveChannel will also work but this is more apt
if (resource instanceof VoiceChannel) {
return resource;
}
return null;
};
Resolver.prototype.resolveChannel = function resolveChannel(resource) {
/*
accepts a Message, Channel, Server, String ID, User
*/
var self = this;
return new Promise(function (resolve, reject) {
var found = null;
if (resource instanceof Message) {
found = resource.channel;
} else if (resource instanceof Channel) {
found = resource;
} else if (resource instanceof Server) {
found = resource.channels.get("id", resource.id);
} else if (resource instanceof String || typeof resource === "string") {
found = self.internal.channels.get("id", resource);
} else if (resource instanceof User) {
// see if a PM exists
var chatFound = false;
for (var _iterator3 = self.internal.private_channels, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var pmchat = _ref3;
if (pmchat.recipient.equals(resource)) {
chatFound = pmchat;
break;
}
}
if (chatFound) {
// a PM already exists!
found = chatFound;
} else {
// PM does not exist :\
self.internal.startPM(resource).then(function (pmchannel) {
return resolve(pmchannel);
})["catch"](function (e) {
return reject(e);
});
return;
}
}
if (found) resolve(found);else reject(new Error("Didn't found anything"));
});
};
return Resolver;
})();
module.exports = Resolver;

@@ -1,7 +0,130 @@

"use strict";var API="https://discordapp.com/api";var Endpoints={ // general endpoints
LOGIN:API + "/auth/login",LOGOUT:API + "/auth/logout",ME:API + "/users/@me",GATEWAY:API + "/gateway",USER_CHANNELS:function USER_CHANNELS(userID){return API + "/users/" + userID + "/channels";},AVATAR:function AVATAR(userID,avatar){return API + "/users/" + userID + "/avatars/" + avatar + ".jpg";},INVITE:function INVITE(id){return API + "/invite/" + id;}, // servers
SERVERS:API + "/guilds",SERVER:function SERVER(serverID){return Endpoints.SERVERS + "/" + serverID;},SERVER_ICON:function SERVER_ICON(serverID,hash){return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg";},SERVER_PRUNE:function SERVER_PRUNE(serverID){return Endpoints.SERVER(serverID) + "/prune";},SERVER_EMBED:function SERVER_EMBED(serverID){return Endpoints.SERVER(serverID) + "/embed";},SERVER_INVITES:function SERVER_INVITES(serverID){return Endpoints.SERVER(serverID) + "/invites";},SERVER_ROLES:function SERVER_ROLES(serverID){return Endpoints.SERVER(serverID) + "/roles";},SERVER_BANS:function SERVER_BANS(serverID){return Endpoints.SERVER(serverID) + "/bans";},SERVER_INTEGRATIONS:function SERVER_INTEGRATIONS(serverID){return Endpoints.SERVER(serverID) + "/integrations";},SERVER_MEMBERS:function SERVER_MEMBERS(serverID){return Endpoints.SERVER(serverID) + "/members";},SERVER_CHANNELS:function SERVER_CHANNELS(serverID){return Endpoints.SERVER(serverID) + "/channels";}, // channels
CHANNELS:API + "/channels",CHANNEL:function CHANNEL(channelID){return Endpoints.CHANNELS + "/" + channelID;},CHANNEL_MESSAGES:function CHANNEL_MESSAGES(channelID){return Endpoints.CHANNEL(channelID) + "/messages";},CHANNEL_INVITES:function CHANNEL_INVITES(channelID){return Endpoints.CHANNEL(channelID) + "/invites";},CHANNEL_TYPING:function CHANNEL_TYPING(channelID){return Endpoints.CHANNEL(channelID) + "/typing";},CHANNEL_PERMISSIONS:function CHANNEL_PERMISSIONS(channelID){return Endpoints.CHANNEL(channelID) + "/permissions";},CHANNEL_MESSAGE:function CHANNEL_MESSAGE(channelID,messageID){return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID;}};var Permissions={ // general
createInstantInvite:1 << 0,kickMembers:1 << 1,banMembers:1 << 2,manageRoles:1 << 3,managePermissions:1 << 3,manageChannels:1 << 4,manageChannel:1 << 4,manageServer:1 << 5, // text
readMessages:1 << 10,sendMessages:1 << 11,sendTTSMessages:1 << 12,manageMessages:1 << 13,embedLinks:1 << 14,attachFiles:1 << 15,readMessageHistory:1 << 16,mentionEveryone:1 << 17, // voice
voiceConnect:1 << 20,voiceSpeak:1 << 21,voiceMuteMembers:1 << 22,voiceDeafenMembers:1 << 23,voiceMoveMembers:1 << 24,voiceUseVAD:1 << 25};var PacketType={READY:"READY",MESSAGE_CREATE:"MESSAGE_CREATE",MESSAGE_UPDATE:"MESSAGE_UPDATE",MESSAGE_DELETE:"MESSAGE_DELETE",SERVER_CREATE:"GUILD_CREATE",SERVER_DELETE:"GUILD_DELETE",SERVER_UPDATE:"GUILD_UPDATE",CHANNEL_CREATE:"CHANNEL_CREATE",CHANNEL_DELETE:"CHANNEL_DELETE",CHANNEL_UPDATE:"CHANNEL_UPDATE",SERVER_ROLE_CREATE:"GUILD_ROLE_CREATE",SERVER_ROLE_DELETE:"GUILD_ROLE_DELETE",SERVER_ROLE_UPDATE:"GUILD_ROLE_UPDATE",SERVER_MEMBER_ADD:"GUILD_MEMBER_ADD",SERVER_MEMBER_REMOVE:"GUILD_MEMBER_REMOVE",SERVER_MEMBER_UPDATE:"GUILD_MEMBER_UPDATE",PRESENCE_UPDATE:"PRESENCE_UPDATE",TYPING:"TYPING_START",SERVER_BAN_ADD:"GUILD_BAN_ADD",SERVER_BAN_REMOVE:"GUILD_BAN_REMOVE"};exports.API_ENDPOINT = API;exports.Endpoints = Endpoints;exports.PacketType = PacketType;exports.Permissions = Permissions;
"use strict";
var API = "https://discordapp.com/api";
var Endpoints = {
// general endpoints
LOGIN: API + "/auth/login",
LOGOUT: API + "/auth/logout",
ME: API + "/users/@me",
GATEWAY: API + "/gateway",
USER_CHANNELS: function USER_CHANNELS(userID) {
return API + "/users/" + userID + "/channels";
},
AVATAR: function AVATAR(userID, avatar) {
return API + "/users/" + userID + "/avatars/" + avatar + ".jpg";
},
INVITE: function INVITE(id) {
return API + "/invite/" + id;
},
// servers
SERVERS: API + "/guilds",
SERVER: function SERVER(serverID) {
return Endpoints.SERVERS + "/" + serverID;
},
SERVER_ICON: function SERVER_ICON(serverID, hash) {
return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg";
},
SERVER_PRUNE: function SERVER_PRUNE(serverID) {
return Endpoints.SERVER(serverID) + "/prune";
},
SERVER_EMBED: function SERVER_EMBED(serverID) {
return Endpoints.SERVER(serverID) + "/embed";
},
SERVER_INVITES: function SERVER_INVITES(serverID) {
return Endpoints.SERVER(serverID) + "/invites";
},
SERVER_ROLES: function SERVER_ROLES(serverID) {
return Endpoints.SERVER(serverID) + "/roles";
},
SERVER_BANS: function SERVER_BANS(serverID) {
return Endpoints.SERVER(serverID) + "/bans";
},
SERVER_INTEGRATIONS: function SERVER_INTEGRATIONS(serverID) {
return Endpoints.SERVER(serverID) + "/integrations";
},
SERVER_MEMBERS: function SERVER_MEMBERS(serverID) {
return Endpoints.SERVER(serverID) + "/members";
},
SERVER_CHANNELS: function SERVER_CHANNELS(serverID) {
return Endpoints.SERVER(serverID) + "/channels";
},
// channels
CHANNELS: API + "/channels",
CHANNEL: function CHANNEL(channelID) {
return Endpoints.CHANNELS + "/" + channelID;
},
CHANNEL_MESSAGES: function CHANNEL_MESSAGES(channelID) {
return Endpoints.CHANNEL(channelID) + "/messages";
},
CHANNEL_INVITES: function CHANNEL_INVITES(channelID) {
return Endpoints.CHANNEL(channelID) + "/invites";
},
CHANNEL_TYPING: function CHANNEL_TYPING(channelID) {
return Endpoints.CHANNEL(channelID) + "/typing";
},
CHANNEL_PERMISSIONS: function CHANNEL_PERMISSIONS(channelID) {
return Endpoints.CHANNEL(channelID) + "/permissions";
},
CHANNEL_MESSAGE: function CHANNEL_MESSAGE(channelID, messageID) {
return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID;
}
};
var Permissions = {
// general
createInstantInvite: 1 << 0,
kickMembers: 1 << 1,
banMembers: 1 << 2,
manageRoles: 1 << 3,
managePermissions: 1 << 3,
manageChannels: 1 << 4,
manageChannel: 1 << 4,
manageServer: 1 << 5,
// text
readMessages: 1 << 10,
sendMessages: 1 << 11,
sendTTSMessages: 1 << 12,
manageMessages: 1 << 13,
embedLinks: 1 << 14,
attachFiles: 1 << 15,
readMessageHistory: 1 << 16,
mentionEveryone: 1 << 17,
// voice
voiceConnect: 1 << 20,
voiceSpeak: 1 << 21,
voiceMuteMembers: 1 << 22,
voiceDeafenMembers: 1 << 23,
voiceMoveMembers: 1 << 24,
voiceUseVAD: 1 << 25
};
var PacketType = {
READY: "READY",
MESSAGE_CREATE: "MESSAGE_CREATE",
MESSAGE_UPDATE: "MESSAGE_UPDATE",
MESSAGE_DELETE: "MESSAGE_DELETE",
SERVER_CREATE: "GUILD_CREATE",
SERVER_DELETE: "GUILD_DELETE",
SERVER_UPDATE: "GUILD_UPDATE",
CHANNEL_CREATE: "CHANNEL_CREATE",
CHANNEL_DELETE: "CHANNEL_DELETE",
CHANNEL_UPDATE: "CHANNEL_UPDATE",
SERVER_ROLE_CREATE: "GUILD_ROLE_CREATE",
SERVER_ROLE_DELETE: "GUILD_ROLE_DELETE",
SERVER_ROLE_UPDATE: "GUILD_ROLE_UPDATE",
SERVER_MEMBER_ADD: "GUILD_MEMBER_ADD",
SERVER_MEMBER_REMOVE: "GUILD_MEMBER_REMOVE",
SERVER_MEMBER_UPDATE: "GUILD_MEMBER_UPDATE",
PRESENCE_UPDATE: "PRESENCE_UPDATE",
TYPING: "TYPING_START",
SERVER_BAN_ADD: "GUILD_BAN_ADD",
SERVER_BAN_REMOVE: "GUILD_BAN_REMOVE"
};
exports.API_ENDPOINT = API;
exports.Endpoints = Endpoints;
exports.PacketType = PacketType;
exports.Permissions = Permissions;

@@ -1,1 +0,18 @@

"use strict";module.exports = {Client:require("./Client/Client"),Channel:require("./Structures/Channel"),ChannelPermissions:require("./Structures/ChannelPermissions"),Invite:require("./Structures/Invite"),Message:require("./Structures/Message"),PermissionOverwrite:require("./Structures/PermissionOverwrite"),PMChannel:require("./Structures/PMChannel"),Role:require("./Structures/Role"),Server:require("./Structures/Server"),ServerChannel:require("./Structures/ServerChannel"),TextChannel:require("./Structures/TextChannel"),User:require("./Structures/User"),VoiceChannel:require("./Structures/VoiceChannel"),Constants:require("./Constants.js")};
"use strict";
module.exports = {
Client: require("./Client/Client"),
Channel: require("./Structures/Channel"),
ChannelPermissions: require("./Structures/ChannelPermissions"),
Invite: require("./Structures/Invite"),
Message: require("./Structures/Message"),
PermissionOverwrite: require("./Structures/PermissionOverwrite"),
PMChannel: require("./Structures/PMChannel"),
Role: require("./Structures/Role"),
Server: require("./Structures/Server"),
ServerChannel: require("./Structures/ServerChannel"),
TextChannel: require("./Structures/TextChannel"),
User: require("./Structures/User"),
VoiceChannel: require("./Structures/VoiceChannel"),
Constants: require("./Constants.js")
};

@@ -1,1 +0,39 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Equality=require("../Util/Equality.js");var Cache=require("../Util/Cache.js");var PermissionOverwrite=require("./PermissionOverwrite.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var Channel=(function(_Equality){_inherits(Channel,_Equality);function Channel(data,client){_classCallCheck(this,Channel);_Equality.call(this);this.id = data.id;this.client = client;}Channel.prototype["delete"] = function _delete(){return this.client.deleteChannel.apply(this.client,reg(this,arguments));};return Channel;})(Equality);module.exports = Channel;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Equality = require("../Util/Equality.js");
var Cache = require("../Util/Cache.js");
var PermissionOverwrite = require("./PermissionOverwrite.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var Channel = (function (_Equality) {
_inherits(Channel, _Equality);
function Channel(data, client) {
_classCallCheck(this, Channel);
_Equality.call(this);
this.id = data.id;
this.client = client;
}
Channel.prototype["delete"] = function _delete() {
return this.client.deleteChannel.apply(this.client, reg(this, arguments));
};
_createClass(Channel, [{
key: "isPrivate",
get: function get() {
return !!this.server;
}
}]);
return Channel;
})(Equality);
module.exports = Channel;

@@ -1,7 +0,75 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Permissions=require("../Constants.js").Permissions;var ChannelPermissions=(function(){function ChannelPermissions(permissions){_classCallCheck(this,ChannelPermissions);this.permissions = permissions;}ChannelPermissions.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general
createInstantInvite:hp(Permissions.createInstantInvite),kickMembers:hp(Permissions.kickMembers),banMembers:hp(Permissions.banMembers),managePermissions:hp(Permissions.managePermissions),manageChannel:hp(Permissions.manageChannel),manageServer:hp(Permissions.manageServer), // text
readMessages:hp(Permissions.readMessages),sendMessages:hp(Permissions.sendMessages),sendTTSMessages:hp(Permissions.sendTTSMessages),manageMessages:hp(Permissions.manageMessages),embedLinks:hp(Permissions.embedLinks),attachFiles:hp(Permissions.attachFiles),readMessageHistory:hp(Permissions.readMessageHistory),mentionEveryone:hp(Permissions.mentionEveryone), // voice
voiceConnect:hp(Permissions.voiceConnect),voiceSpeak:hp(Permissions.voiceSpeak),voiceMuteMembers:hp(Permissions.voiceMuteMembers),voiceDeafenMembers:hp(Permissions.voiceDeafenMembers),voiceMoveMembers:hp(Permissions.voiceMoveMembers),voiceUseVAD:hp(Permissions.voiceUseVAD)};};ChannelPermissions.prototype.serialize = function serialize(){ // ;n;
return this.serialise();};ChannelPermissions.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed
if(!!(this.permissions & Permissions.manageRoles)){ // manageRoles allowed, they have all permissions
return true;}}return !!(this.permissions & perm);};return ChannelPermissions;})();module.exports = ChannelPermissions;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Permissions = require("../Constants.js").Permissions;
var ChannelPermissions = (function () {
function ChannelPermissions(permissions) {
_classCallCheck(this, ChannelPermissions);
this.permissions = permissions;
}
ChannelPermissions.prototype.serialise = function serialise(explicit) {
var _this = this;
var hp = function hp(perm) {
return _this.hasPermission(perm, explicit);
};
return {
// general
createInstantInvite: hp(Permissions.createInstantInvite),
kickMembers: hp(Permissions.kickMembers),
banMembers: hp(Permissions.banMembers),
managePermissions: hp(Permissions.managePermissions),
manageChannel: hp(Permissions.manageChannel),
manageServer: hp(Permissions.manageServer),
// text
readMessages: hp(Permissions.readMessages),
sendMessages: hp(Permissions.sendMessages),
sendTTSMessages: hp(Permissions.sendTTSMessages),
manageMessages: hp(Permissions.manageMessages),
embedLinks: hp(Permissions.embedLinks),
attachFiles: hp(Permissions.attachFiles),
readMessageHistory: hp(Permissions.readMessageHistory),
mentionEveryone: hp(Permissions.mentionEveryone),
// voice
voiceConnect: hp(Permissions.voiceConnect),
voiceSpeak: hp(Permissions.voiceSpeak),
voiceMuteMembers: hp(Permissions.voiceMuteMembers),
voiceDeafenMembers: hp(Permissions.voiceDeafenMembers),
voiceMoveMembers: hp(Permissions.voiceMoveMembers),
voiceUseVAD: hp(Permissions.voiceUseVAD)
};
};
ChannelPermissions.prototype.serialize = function serialize() {
// ;n;
return this.serialise();
};
ChannelPermissions.prototype.hasPermission = function hasPermission(perm) {
var explicit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (perm instanceof String || typeof perm === "string") {
perm = Permissions[perm];
}
if (!perm) {
return false;
}
if (!explicit) {
// implicit permissions allowed
if (!!(this.permissions & Permissions.manageRoles)) {
// manageRoles allowed, they have all permissions
return true;
}
}
return !!(this.permissions & perm);
};
return ChannelPermissions;
})();
module.exports = ChannelPermissions;

@@ -1,1 +0,32 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Server=require("./Server.js");var ServerChannel=require("./ServerChannel.js");var Invite=(function(){function Invite(data,chan,client){_classCallCheck(this,Invite);this.maxAge = data.max_age;this.code = data.code;this.server = chan.server;this.channel = chan;this.revoked = data.revoked;this.createdAt = Date.parse(data.created_at);this.temporary = data.temporary;this.uses = data.uses;this.maxUses = data.uses;this.inviter = client.internal.users.get("id",data.inviter.id);this.xkcd = data.xkcdpass;}Invite.prototype.toString = function toString(){return "https://discord.gg/" + this.code;};return Invite;})();module.exports = Invite;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Server = require("./Server.js");
var ServerChannel = require("./ServerChannel.js");
var Invite = (function () {
function Invite(data, chan, client) {
_classCallCheck(this, Invite);
this.maxAge = data.max_age;
this.code = data.code;
this.server = chan.server;
this.channel = chan;
this.revoked = data.revoked;
this.createdAt = Date.parse(data.created_at);
this.temporary = data.temporary;
this.uses = data.uses;
this.maxUses = data.uses;
this.inviter = client.internal.users.get("id", data.inviter.id);
this.xkcd = data.xkcdpass;
}
Invite.prototype.toString = function toString() {
return "https://discord.gg/" + this.code;
};
return Invite;
})();
module.exports = Invite;

@@ -1,4 +0,87 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Cache=require("../Util/Cache.js");var User=require("./User.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var Equality=require("../Util/Equality");var Message=(function(_Equality){_inherits(Message,_Equality);function Message(data,channel,client){var _this=this;_classCallCheck(this,Message);_Equality.call(this);this.channel = channel;this.client = client;this.nonce = data.nonce;this.attachments = data.attachments;this.tts = data.tts;this.embeds = data.embeds;this.timestamp = Date.parse(data.timestamp);this.everyoneMentioned = data.mention_everyone;this.id = data.id;if(data.edited_timestamp)this.editedTimestamp = Date.parse(data.edited_timestamp);if(data.author instanceof User)this.author = data.author;else this.author = client.internal.users.add(new User(data.author,client));this.content = data.content;this.mentions = new Cache();data.mentions.forEach(function(mention){ // this is .add and not .get because it allows the bot to cache
// users from messages from logs who may have left the server and were
// not previously cached.
if(mention instanceof User)_this.mentions.push(mention);else _this.mentions.add(client.internal.users.add(new User(mention,client)));});}Message.prototype.isMentioned = function isMentioned(user){user = this.client.internal.resolver.resolveUser(user);if(user){return this.mentions.has("id",user.id);}else {return false;}};Message.prototype.toString = function toString(){return this.content;};Message.prototype["delete"] = function _delete(){return this.client.deleteMessage.apply(this.client,reg(this,arguments));};Message.prototype.update = function update(){return this.client.updateMessage.apply(this.client,reg(this,arguments));};Message.prototype.reply = function reply(){return this.client.reply.apply(this.client,reg(this,arguments));};Message.prototype.replyTTS = function replyTTS(){return this.client.replyTTS.apply(this.client,reg(this,arguments));};return Message;})(Equality);module.exports = Message;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Cache = require("../Util/Cache.js");
var User = require("./User.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var Equality = require("../Util/Equality");
var Message = (function (_Equality) {
_inherits(Message, _Equality);
function Message(data, channel, client) {
var _this = this;
_classCallCheck(this, Message);
_Equality.call(this);
this.channel = channel;
this.client = client;
this.nonce = data.nonce;
this.attachments = data.attachments;
this.tts = data.tts;
this.embeds = data.embeds;
this.timestamp = Date.parse(data.timestamp);
this.everyoneMentioned = data.mention_everyone;
this.id = data.id;
if (data.edited_timestamp) this.editedTimestamp = Date.parse(data.edited_timestamp);
if (data.author instanceof User) this.author = data.author;else this.author = client.internal.users.add(new User(data.author, client));
this.content = data.content;
this.mentions = new Cache();
data.mentions.forEach(function (mention) {
// this is .add and not .get because it allows the bot to cache
// users from messages from logs who may have left the server and were
// not previously cached.
if (mention instanceof User) _this.mentions.push(mention);else _this.mentions.add(client.internal.users.add(new User(mention, client)));
});
}
Message.prototype.isMentioned = function isMentioned(user) {
user = this.client.internal.resolver.resolveUser(user);
if (user) {
return this.mentions.has("id", user.id);
} else {
return false;
}
};
Message.prototype.toString = function toString() {
return this.content;
};
Message.prototype["delete"] = function _delete() {
return this.client.deleteMessage.apply(this.client, reg(this, arguments));
};
Message.prototype.update = function update() {
return this.client.updateMessage.apply(this.client, reg(this, arguments));
};
Message.prototype.reply = function reply() {
return this.client.reply.apply(this.client, reg(this, arguments));
};
Message.prototype.replyTTS = function replyTTS() {
return this.client.replyTTS.apply(this.client, reg(this, arguments));
};
_createClass(Message, [{
key: "sender",
get: function get() {
return this.author;
}
}]);
return Message;
})(Equality);
module.exports = Message;

@@ -1,6 +0,86 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Permissions=require("../Constants.js").Permissions;var PermissionOverwrite=(function(){function PermissionOverwrite(data){_classCallCheck(this,PermissionOverwrite);this.id = data.id;this.type = data.type; // member or role
this.deny = data.deny;this.allow = data.allow;} // returns an array of allowed permissions
PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray){var _this=this;allowedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){_this.allow |= 1 << permission;}});};PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray){var _this2=this;deniedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){_this2.deny |= 1 << permission;}});};_createClass(PermissionOverwrite,[{key:"allowed",get:function get(){var allowed=[];for(var permName in Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites.
continue;}if(!!(this.allow & Permissions[permName])){allowed.push(permName);}}return allowed;} // returns an array of denied permissions
},{key:"denied",get:function get(){var denied=[];for(var permName in Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites.
continue;}if(!!(this.deny & Permissions[permName])){denied.push(permName);}}return denied;}}]);return PermissionOverwrite;})();module.exports = PermissionOverwrite;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Permissions = require("../Constants.js").Permissions;
var PermissionOverwrite = (function () {
function PermissionOverwrite(data) {
_classCallCheck(this, PermissionOverwrite);
this.id = data.id;
this.type = data.type; // member or role
this.deny = data.deny;
this.allow = data.allow;
}
// returns an array of allowed permissions
PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray) {
var _this = this;
allowedArray.forEach(function (permission) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
_this.allow |= 1 << permission;
}
});
};
PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray) {
var _this2 = this;
deniedArray.forEach(function (permission) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
_this2.deny |= 1 << permission;
}
});
};
_createClass(PermissionOverwrite, [{
key: "allowed",
get: function get() {
var allowed = [];
for (var permName in Permissions) {
if (permName === "manageRoles" || permName === "manageChannels") {
// these permissions do not exist in overwrites.
continue;
}
if (!!(this.allow & Permissions[permName])) {
allowed.push(permName);
}
}
return allowed;
}
// returns an array of denied permissions
}, {
key: "denied",
get: function get() {
var denied = [];
for (var permName in Permissions) {
if (permName === "manageRoles" || permName === "manageChannels") {
// these permissions do not exist in overwrites.
continue;
}
if (!!(this.deny & Permissions[permName])) {
denied.push(permName);
}
}
return denied;
}
}]);
return PermissionOverwrite;
})();
module.exports = PermissionOverwrite;

@@ -1,1 +0,53 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Channel=require("./Channel.js");var User=require("./User.js");var Equality=require("../Util/Equality.js");var Cache=require("../Util/Cache.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var PMChannel=(function(_Channel){_inherits(PMChannel,_Channel);function PMChannel(data,client){_classCallCheck(this,PMChannel);_Channel.call(this,data,client);this.type = data.type || "text";this.lastMessageId = data.last_message_id;this.messages = new Cache("id",1000);this.recipient = this.client.internal.users.add(new User(data.recipient,this.client));} /* warning! may return null */PMChannel.prototype.toString = function toString(){return this.recipient.toString();};PMChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,reg(this,arguments));};PMChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,reg(this,arguments));};_createClass(PMChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return PMChannel;})(Channel);module.exports = PMChannel;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Channel = require("./Channel.js");
var User = require("./User.js");
var Equality = require("../Util/Equality.js");
var Cache = require("../Util/Cache.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var PMChannel = (function (_Channel) {
_inherits(PMChannel, _Channel);
function PMChannel(data, client) {
_classCallCheck(this, PMChannel);
_Channel.call(this, data, client);
this.type = data.type || "text";
this.lastMessageId = data.last_message_id;
this.messages = new Cache("id", 1000);
this.recipient = this.client.internal.users.add(new User(data.recipient, this.client));
}
/* warning! may return null */
PMChannel.prototype.toString = function toString() {
return this.recipient.toString();
};
PMChannel.prototype.sendMessage = function sendMessage() {
return this.client.sendMessage.apply(this.client, reg(this, arguments));
};
PMChannel.prototype.sendTTSMessage = function sendTTSMessage() {
return this.client.sendTTSMessage.apply(this.client, reg(this, arguments));
};
_createClass(PMChannel, [{
key: "lastMessage",
get: function get() {
return this.messages.get("id", this.lastMessageID);
}
}]);
return PMChannel;
})(Channel);
module.exports = PMChannel;

@@ -1,3 +0,8 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Permissions=require("../Constants.js").Permissions; /*
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Permissions = require("../Constants.js").Permissions;
/*
example data

@@ -12,13 +17,124 @@

color: 0 }
*/var DefaultRole=[Permissions.createInstantInvite,Permissions.readMessages,Permissions.readMessageHistory,Permissions.sendMessages,Permissions.sendTTSMessages,Permissions.embedLinks,Permissions.attachFiles,Permissions.readMessageHistory,Permissions.mentionEveryone,Permissions.voiceConnect,Permissions.voiceSpeak,Permissions.voiceUseVAD].reduce(function(previous,current){return previous | current;},0);var Role=(function(){function Role(data,server,client){_classCallCheck(this,Role);this.position = data.position || -1;this.permissions = data.permissions || (data.name === "@everyone"?DefaultRole:0);this.name = data.name || "@everyone";this.managed = data.managed || false;this.id = data.id;this.hoist = data.hoist || false;this.color = data.color || 0;this.server = server;this.client = client;}Role.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general
createInstantInvite:hp(Permissions.createInstantInvite),kickMembers:hp(Permissions.kickMembers),banMembers:hp(Permissions.banMembers),manageRoles:hp(Permissions.manageRoles),manageChannels:hp(Permissions.manageChannels),manageServer:hp(Permissions.manageServer), // text
readMessages:hp(Permissions.readMessages),sendMessages:hp(Permissions.sendMessages),sendTTSMessages:hp(Permissions.sendTTSMessages),manageMessages:hp(Permissions.manageMessages),embedLinks:hp(Permissions.embedLinks),attachFiles:hp(Permissions.attachFiles),readMessageHistory:hp(Permissions.readMessageHistory),mentionEveryone:hp(Permissions.mentionEveryone), // voice
voiceConnect:hp(Permissions.voiceConnect),voiceSpeak:hp(Permissions.voiceSpeak),voiceMuteMembers:hp(Permissions.voiceMuteMembers),voiceDeafenMembers:hp(Permissions.voiceDeafenMembers),voiceMoveMembers:hp(Permissions.voiceMoveMembers),voiceUseVAD:hp(Permissions.voiceUseVAD)};};Role.prototype.serialize = function serialize(){ // ;n;
return this.serialise();};Role.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed
if(!!(this.permissions & Permissions.manageRoles)){ // manageRoles allowed, they have all permissions
return true;}} // e.g.
// !!(36953089 & Permissions.manageRoles) = not allowed to manage roles
// !!(36953089 & (1 << 21)) = voice speak allowed
return !!(this.permissions & perm);};Role.prototype.setPermission = function setPermission(permission,value){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){ // valid permission
if(value){this.permissions |= permission;}else {this.permissions &= ~permission;}}};Role.prototype.setPermissions = function setPermissions(obj){var _this2=this;obj.forEach(function(value,permission){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){ // valid permission
_this2.setPermission(permission,value);}});};Role.prototype.colorAsHex = function colorAsHex(){var val=this.color.toString();while(val.length < 6) {val = "0" + val;}return "#" + val;};return Role;})();module.exports = Role;
*/
var DefaultRole = [Permissions.createInstantInvite, Permissions.readMessages, Permissions.readMessageHistory, Permissions.sendMessages, Permissions.sendTTSMessages, Permissions.embedLinks, Permissions.attachFiles, Permissions.readMessageHistory, Permissions.mentionEveryone, Permissions.voiceConnect, Permissions.voiceSpeak, Permissions.voiceUseVAD].reduce(function (previous, current) {
return previous | current;
}, 0);
var Role = (function () {
function Role(data, server, client) {
_classCallCheck(this, Role);
this.position = data.position || -1;
this.permissions = data.permissions || (data.name === "@everyone" ? DefaultRole : 0);
this.name = data.name || "@everyone";
this.managed = data.managed || false;
this.id = data.id;
this.hoist = data.hoist || false;
this.color = data.color || 0;
this.server = server;
this.client = client;
}
Role.prototype.serialise = function serialise(explicit) {
var _this = this;
var hp = function hp(perm) {
return _this.hasPermission(perm, explicit);
};
return {
// general
createInstantInvite: hp(Permissions.createInstantInvite),
kickMembers: hp(Permissions.kickMembers),
banMembers: hp(Permissions.banMembers),
manageRoles: hp(Permissions.manageRoles),
manageChannels: hp(Permissions.manageChannels),
manageServer: hp(Permissions.manageServer),
// text
readMessages: hp(Permissions.readMessages),
sendMessages: hp(Permissions.sendMessages),
sendTTSMessages: hp(Permissions.sendTTSMessages),
manageMessages: hp(Permissions.manageMessages),
embedLinks: hp(Permissions.embedLinks),
attachFiles: hp(Permissions.attachFiles),
readMessageHistory: hp(Permissions.readMessageHistory),
mentionEveryone: hp(Permissions.mentionEveryone),
// voice
voiceConnect: hp(Permissions.voiceConnect),
voiceSpeak: hp(Permissions.voiceSpeak),
voiceMuteMembers: hp(Permissions.voiceMuteMembers),
voiceDeafenMembers: hp(Permissions.voiceDeafenMembers),
voiceMoveMembers: hp(Permissions.voiceMoveMembers),
voiceUseVAD: hp(Permissions.voiceUseVAD)
};
};
Role.prototype.serialize = function serialize() {
// ;n;
return this.serialise();
};
Role.prototype.hasPermission = function hasPermission(perm) {
var explicit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (perm instanceof String || typeof perm === "string") {
perm = Permissions[perm];
}
if (!perm) {
return false;
}
if (!explicit) {
// implicit permissions allowed
if (!!(this.permissions & Permissions.manageRoles)) {
// manageRoles allowed, they have all permissions
return true;
}
}
// e.g.
// !!(36953089 & Permissions.manageRoles) = not allowed to manage roles
// !!(36953089 & (1 << 21)) = voice speak allowed
return !!(this.permissions & perm);
};
Role.prototype.setPermission = function setPermission(permission, value) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
// valid permission
if (value) {
this.permissions |= permission;
} else {
this.permissions &= ~permission;
}
}
};
Role.prototype.setPermissions = function setPermissions(obj) {
var _this2 = this;
obj.forEach(function (value, permission) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
// valid permission
_this2.setPermission(permission, value);
}
});
};
Role.prototype.colorAsHex = function colorAsHex() {
var val = this.color.toString();
while (val.length < 6) {
val = "0" + val;
}
return "#" + val;
};
return Role;
})();
module.exports = Role;

@@ -1,1 +0,169 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Equality=require("../Util/Equality.js");var Endpoints=require("../Constants.js").Endpoints;var Cache=require("../Util/Cache.js");var User=require("./User.js");var TextChannel=require("./TextChannel.js");var VoiceChannel=require("./VoiceChannel.js");var Role=require("./Role.js");var strictKeys=["region","ownerID","name","id","icon","afkTimeout","afkChannelID"];var Server=(function(_Equality){_inherits(Server,_Equality);function Server(data,client){var _this=this;_classCallCheck(this,Server);_Equality.call(this);var self=this;this.client = client;this.region = data.region;this.ownerID = data.owner_id;this.name = data.name;this.id = data.id;this.members = new Cache();this.channels = new Cache();this.roles = new Cache();this.icon = data.icon;this.afkTimeout = data.afkTimeout;this.afkChannelID = data.afk_channel_id;this.memberMap = {};var self=this;data.roles.forEach(function(dataRole){_this.roles.add(new Role(dataRole,_this,client));});data.members.forEach(function(dataUser){_this.memberMap[dataUser.user.id] = {roles:dataUser.roles.map(function(pid){return self.roles.get("id",pid);}),mute:dataUser.mute,deaf:dataUser.deaf,joinedAt:Date.parse(dataUser.joined_at)};var user=client.internal.users.add(new User(dataUser.user,client));_this.members.add(user);});data.channels.forEach(function(dataChannel){if(dataChannel.type === "text"){var channel=client.internal.channels.add(new TextChannel(dataChannel,client,_this));_this.channels.add(channel);}else {var channel=client.internal.channels.add(new VoiceChannel(dataChannel,client,_this));_this.channels.add(channel);}});if(data.presences){for(var _iterator=data.presences,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var presence=_ref;var user=client.internal.users.get("id",presence.user.id);if(user){user.status = presence.status;user.gameID = presence.game_id;}}}}Server.prototype.rolesOfUser = function rolesOfUser(user){user = this.client.internal.resolver.resolveUser(user);if(user){return this.memberMap[user.id]?this.memberMap[user.id].roles:[];}else {return null;}};Server.prototype.rolesOf = function rolesOf(user){return this.rolesOfUser(user);};Server.prototype.toString = function toString(){return this.name;};Server.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof Server){for(var _iterator2=strictKeys,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var key=_ref2;if(obj[key] !== this[key]){return false;}}}else {return false;}return true;};_createClass(Server,[{key:"iconURL",get:function get(){if(!this.icon){return null;}else {return Endpoints.SERVER_ICON(this.id,this.icon);}}},{key:"afkChannel",get:function get(){return this.channels.get("id",this.afkChannelID);}},{key:"defaultChannel",get:function get(){return this.channels.get("id",this.id);}},{key:"owner",get:function get(){return this.members.get("id",this.ownerID);}}]);return Server;})(Equality);module.exports = Server;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Equality = require("../Util/Equality.js");
var Endpoints = require("../Constants.js").Endpoints;
var Cache = require("../Util/Cache.js");
var User = require("./User.js");
var TextChannel = require("./TextChannel.js");
var VoiceChannel = require("./VoiceChannel.js");
var Role = require("./Role.js");
var strictKeys = ["region", "ownerID", "name", "id", "icon", "afkTimeout", "afkChannelID"];
var Server = (function (_Equality) {
_inherits(Server, _Equality);
function Server(data, client) {
var _this = this;
_classCallCheck(this, Server);
_Equality.call(this);
var self = this;
this.client = client;
this.region = data.region;
this.ownerID = data.owner_id;
this.name = data.name;
this.id = data.id;
this.members = new Cache();
this.channels = new Cache();
this.roles = new Cache();
this.icon = data.icon;
this.afkTimeout = data.afkTimeout;
this.afkChannelID = data.afk_channel_id;
this.memberMap = {};
var self = this;
data.roles.forEach(function (dataRole) {
_this.roles.add(new Role(dataRole, _this, client));
});
data.members.forEach(function (dataUser) {
_this.memberMap[dataUser.user.id] = {
roles: dataUser.roles.map(function (pid) {
return self.roles.get("id", pid);
}),
mute: dataUser.mute,
deaf: dataUser.deaf,
joinedAt: Date.parse(dataUser.joined_at)
};
var user = client.internal.users.add(new User(dataUser.user, client));
_this.members.add(user);
});
data.channels.forEach(function (dataChannel) {
if (dataChannel.type === "text") {
var channel = client.internal.channels.add(new TextChannel(dataChannel, client, _this));
_this.channels.add(channel);
} else {
var channel = client.internal.channels.add(new VoiceChannel(dataChannel, client, _this));
_this.channels.add(channel);
}
});
if (data.presences) {
for (var _iterator = data.presences, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var presence = _ref;
var user = client.internal.users.get("id", presence.user.id);
if (user) {
user.status = presence.status;
user.gameID = presence.game_id;
}
}
}
}
Server.prototype.rolesOfUser = function rolesOfUser(user) {
user = this.client.internal.resolver.resolveUser(user);
if (user) {
return this.memberMap[user.id] ? this.memberMap[user.id].roles : [];
} else {
return null;
}
};
Server.prototype.rolesOf = function rolesOf(user) {
return this.rolesOfUser(user);
};
Server.prototype.toString = function toString() {
return this.name;
};
Server.prototype.equalsStrict = function equalsStrict(obj) {
if (obj instanceof Server) {
for (var _iterator2 = strictKeys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var key = _ref2;
if (obj[key] !== this[key]) {
return false;
}
}
} else {
return false;
}
return true;
};
_createClass(Server, [{
key: "iconURL",
get: function get() {
if (!this.icon) {
return null;
} else {
return Endpoints.SERVER_ICON(this.id, this.icon);
}
}
}, {
key: "afkChannel",
get: function get() {
return this.channels.get("id", this.afkChannelID);
}
}, {
key: "defaultChannel",
get: function get() {
return this.channels.get("id", this.id);
}
}, {
key: "owner",
get: function get() {
return this.members.get("id", this.ownerID);
}
}]);
return Server;
})(Equality);
module.exports = Server;

@@ -1,1 +0,117 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Channel=require("./Channel.js");var Cache=require("../Util/Cache.js");var PermissionOverwrite=require("./PermissionOverwrite.js");var ChannelPermissions=require("./ChannelPermissions.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var ServerChannel=(function(_Channel){_inherits(ServerChannel,_Channel);function ServerChannel(data,client,server){var _this=this;_classCallCheck(this,ServerChannel);_Channel.call(this,data,client);this.name = data.name;this.type = data.type;this.position = data.position;this.permissionOverwrites = new Cache();this.server = server;data.permission_overwrites.forEach(function(permission){_this.permissionOverwrites.add(new PermissionOverwrite(permission));});}ServerChannel.prototype.permissionsOf = function permissionsOf(user){user = this.client.internal.resolver.resolveUser(user);if(user){if(this.server.owner.equals(user)){return new ChannelPermissions(4294967295);}var everyoneRole=this.server.roles.get("name","@everyone");var userRoles=[everyoneRole].concat(this.server.rolesOf(user) || []);var userRolesID=userRoles.map(function(v){return v.id;});var roleOverwrites=[],memberOverwrites=[];this.permissionOverwrites.forEach(function(overwrite){if(overwrite.type === "member" && overwrite.id === user.id){memberOverwrites.push(overwrite);}else if(overwrite.type === "role" && overwrite.id in userRolesID){roleOverwrites.push(overwrite);}});var permissions=0;for(var _iterator=userRoles,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var serverRole=_ref;permissions |= serverRole.permissions;}for(var _iterator2=roleOverwrites.concat(memberOverwrites),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var overwrite=_ref2;permissions = permissions & ~overwrite.deny;permissions = permissions | overwrite.allow;}return new ChannelPermissions(permissions);}else {return null;}};ServerChannel.prototype.permsOf = function permsOf(user){return this.permissionsOf(user);};ServerChannel.prototype.mention = function mention(){return "<#" + this.id + ">";};ServerChannel.prototype.toString = function toString(){return this.mention();};ServerChannel.prototype.setName = function setName(){return this.client.setChannelName.apply(this.client,reg(this,arguments));};return ServerChannel;})(Channel);module.exports = ServerChannel;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Channel = require("./Channel.js");
var Cache = require("../Util/Cache.js");
var PermissionOverwrite = require("./PermissionOverwrite.js");
var ChannelPermissions = require("./ChannelPermissions.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var ServerChannel = (function (_Channel) {
_inherits(ServerChannel, _Channel);
function ServerChannel(data, client, server) {
var _this = this;
_classCallCheck(this, ServerChannel);
_Channel.call(this, data, client);
this.name = data.name;
this.type = data.type;
this.position = data.position;
this.permissionOverwrites = new Cache();
this.server = server;
data.permission_overwrites.forEach(function (permission) {
_this.permissionOverwrites.add(new PermissionOverwrite(permission));
});
}
ServerChannel.prototype.permissionsOf = function permissionsOf(user) {
user = this.client.internal.resolver.resolveUser(user);
if (user) {
if (this.server.owner.equals(user)) {
return new ChannelPermissions(4294967295);
}
var everyoneRole = this.server.roles.get("name", "@everyone");
var userRoles = [everyoneRole].concat(this.server.rolesOf(user) || []);
var userRolesID = userRoles.map(function (v) {
return v.id;
});
var roleOverwrites = [],
memberOverwrites = [];
this.permissionOverwrites.forEach(function (overwrite) {
if (overwrite.type === "member" && overwrite.id === user.id) {
memberOverwrites.push(overwrite);
} else if (overwrite.type === "role" && overwrite.id in userRolesID) {
roleOverwrites.push(overwrite);
}
});
var permissions = 0;
for (var _iterator = userRoles, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var serverRole = _ref;
permissions |= serverRole.permissions;
}
for (var _iterator2 = roleOverwrites.concat(memberOverwrites), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var overwrite = _ref2;
permissions = permissions & ~overwrite.deny;
permissions = permissions | overwrite.allow;
}
return new ChannelPermissions(permissions);
} else {
return null;
}
};
ServerChannel.prototype.permsOf = function permsOf(user) {
return this.permissionsOf(user);
};
ServerChannel.prototype.mention = function mention() {
return "<#" + this.id + ">";
};
ServerChannel.prototype.toString = function toString() {
return this.mention();
};
ServerChannel.prototype.setName = function setName() {
return this.client.setChannelName.apply(this.client, reg(this, arguments));
};
return ServerChannel;
})(Channel);
module.exports = ServerChannel;

@@ -1,1 +0,58 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var ServerChannel=require("./ServerChannel.js");var Cache=require("../Util/Cache.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var TextChannel=(function(_ServerChannel){_inherits(TextChannel,_ServerChannel);function TextChannel(data,client,server){_classCallCheck(this,TextChannel);_ServerChannel.call(this,data,client,server);this.topic = data.topic;this.lastMessageID = data.last_message_id;this.messages = new Cache("id",client.options.maximumMessages);} /* warning! may return null */TextChannel.prototype.setTopic = function setTopic(){return this.client.setTopic.apply(this.client,reg(this,arguments));};TextChannel.prototype.setNameAndTopic = function setNameAndTopic(){return this.client.setChannelNameAndTopic.apply(this.client,reg(this,arguments));};TextChannel.prototype.update = function update(){return this.client.updateChannel.apply(this.client,reg(this,arguments));};TextChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,reg(this,arguments));};TextChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,reg(this,arguments));};_createClass(TextChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return TextChannel;})(ServerChannel);module.exports = TextChannel;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ServerChannel = require("./ServerChannel.js");
var Cache = require("../Util/Cache.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var TextChannel = (function (_ServerChannel) {
_inherits(TextChannel, _ServerChannel);
function TextChannel(data, client, server) {
_classCallCheck(this, TextChannel);
_ServerChannel.call(this, data, client, server);
this.topic = data.topic;
this.lastMessageID = data.last_message_id;
this.messages = new Cache("id", client.options.maximumMessages);
}
/* warning! may return null */
TextChannel.prototype.setTopic = function setTopic() {
return this.client.setTopic.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.setNameAndTopic = function setNameAndTopic() {
return this.client.setChannelNameAndTopic.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.update = function update() {
return this.client.updateChannel.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.sendMessage = function sendMessage() {
return this.client.sendMessage.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.sendTTSMessage = function sendTTSMessage() {
return this.client.sendTTSMessage.apply(this.client, reg(this, arguments));
};
_createClass(TextChannel, [{
key: "lastMessage",
get: function get() {
return this.messages.get("id", this.lastMessageID);
}
}]);
return TextChannel;
})(ServerChannel);
module.exports = TextChannel;

@@ -1,1 +0,58 @@

"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Equality=require("../Util/Equality.js");var Endpoints=require("../Constants.js").Endpoints;var User=(function(_Equality){_inherits(User,_Equality);function User(data,client){_classCallCheck(this,User);_Equality.call(this);this.client = client;this.username = data.username;this.discriminator = data.discriminator;this.id = data.id;this.avatar = data.avatar;this.status = data.status || "offline";this.gameID = data.game_id || null;this.typing = {since:null,channel:null};}User.prototype.mention = function mention(){return "<@" + this.id + ">";};User.prototype.toString = function toString(){return this.mention();};User.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof User)return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && this.gameID === obj.gameID;else return false;};_createClass(User,[{key:"avatarURL",get:function get(){if(!this.avatar){return null;}else {return Endpoints.AVATAR(this.id,this.avatar);}}}]);return User;})(Equality);module.exports = User;
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Equality = require("../Util/Equality.js");
var Endpoints = require("../Constants.js").Endpoints;
var User = (function (_Equality) {
_inherits(User, _Equality);
function User(data, client) {
_classCallCheck(this, User);
_Equality.call(this);
this.client = client;
this.username = data.username;
this.discriminator = data.discriminator;
this.id = data.id;
this.avatar = data.avatar;
this.status = data.status || "offline";
this.gameID = data.game_id || null;
this.typing = {
since: null,
channel: null
};
}
User.prototype.mention = function mention() {
return "<@" + this.id + ">";
};
User.prototype.toString = function toString() {
return this.mention();
};
User.prototype.equalsStrict = function equalsStrict(obj) {
if (obj instanceof User) return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && this.gameID === obj.gameID;else return false;
};
_createClass(User, [{
key: "avatarURL",
get: function get() {
if (!this.avatar) {
return null;
} else {
return Endpoints.AVATAR(this.id, this.avatar);
}
}
}]);
return User;
})(Equality);
module.exports = User;

@@ -1,1 +0,21 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var ServerChannel=require("./ServerChannel.js");var VoiceChannel=(function(_ServerChannel){_inherits(VoiceChannel,_ServerChannel);function VoiceChannel(data,client,server){_classCallCheck(this,VoiceChannel);_ServerChannel.call(this,data,client,server);}return VoiceChannel;})(ServerChannel);module.exports = VoiceChannel;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ServerChannel = require("./ServerChannel.js");
var VoiceChannel = (function (_ServerChannel) {
_inherits(VoiceChannel, _ServerChannel);
function VoiceChannel(data, client, server) {
_classCallCheck(this, VoiceChannel);
_ServerChannel.call(this, data, client, server);
}
return VoiceChannel;
})(ServerChannel);
module.exports = VoiceChannel;

@@ -1,1 +0,5 @@

"use strict";exports.reg = function(c,a){return [c].concat(Array.prototype.slice.call(a));};
"use strict";
exports.reg = function (c, a) {
return [c].concat(Array.prototype.slice.call(a));
};

@@ -1,1 +0,102 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Cache=(function(_Array){_inherits(Cache,_Array);function Cache(discrim,limit){_classCallCheck(this,Cache);_Array.call(this);this.discrim = discrim || "id";}Cache.prototype.get = function get(key,value){var found=null;this.forEach(function(val,index,array){if(val.hasOwnProperty(key) && val[key] == value){found = val;return;}});return found;};Cache.prototype.has = function has(key,value){return !!this.get(key,value);};Cache.prototype.getAll = function getAll(key,value){var found=new Cache(this.discrim);this.forEach(function(val,index,array){if(val.hasOwnProperty(key) && val[key] == value){found.push(val);return;}});return found;};Cache.prototype.add = function add(data){var exit=false;for(var _iterator=this,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var item=_ref;if(item[this.discrim] === data[this.discrim]){exit = item;break;}}if(exit){return exit;}else {if(this.limit && this.length >= this.limit){this.splice(0,1);}this.push(data);return data;}};Cache.prototype.update = function update(old,data){var item=this.get(this.discrim,old[this.discrim]);if(item){var index=this.indexOf(item);this[index] = data;return this[index];}else {return false;}};Cache.prototype.remove = function remove(data){var index=this.indexOf(data);if(~index){this.splice(index,1);}else {var item=this.get(this.discrim,data[this.discrim]);if(item){this.splice(this.indexOf(item),1);}}return false;};return Cache;})(Array);module.exports = Cache;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Cache = (function (_Array) {
_inherits(Cache, _Array);
function Cache(discrim, limit) {
_classCallCheck(this, Cache);
_Array.call(this);
this.discrim = discrim || "id";
}
Cache.prototype.get = function get(key, value) {
var found = null;
this.forEach(function (val, index, array) {
if (val.hasOwnProperty(key) && val[key] == value) {
found = val;
return;
}
});
return found;
};
Cache.prototype.has = function has(key, value) {
return !!this.get(key, value);
};
Cache.prototype.getAll = function getAll(key, value) {
var found = new Cache(this.discrim);
this.forEach(function (val, index, array) {
if (val.hasOwnProperty(key) && val[key] == value) {
found.push(val);
return;
}
});
return found;
};
Cache.prototype.add = function add(data) {
var exit = false;
for (var _iterator = this, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var item = _ref;
if (item[this.discrim] === data[this.discrim]) {
exit = item;
break;
}
}
if (exit) {
return exit;
} else {
if (this.limit && this.length >= this.limit) {
this.splice(0, 1);
}
this.push(data);
return data;
}
};
Cache.prototype.update = function update(old, data) {
var item = this.get(this.discrim, old[this.discrim]);
if (item) {
var index = this.indexOf(item);
this[index] = data;
return this[index];
} else {
return false;
}
};
Cache.prototype.remove = function remove(data) {
var index = this.indexOf(data);
if (~index) {
this.splice(index, 1);
} else {
var item = this.get(this.discrim, data[this.discrim]);
if (item) {
this.splice(this.indexOf(item), 1);
}
}
return false;
};
return Cache;
})(Array);
module.exports = Cache;

@@ -11,3 +11,36 @@ /*

Instead, use objectThatExtendsEquality.equals()
*/"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Equality=(function(){function Equality(){_classCallCheck(this,Equality);}Equality.prototype.equals = function equals(object){if(object && object[this.eqDiscriminator] == this[this.eqDiscriminator]){return true;}return false;};Equality.prototype.equalsStrict = function equalsStrict(object){ // override per class type
return;};_createClass(Equality,[{key:"eqDiscriminator",get:function get(){return "id";}}]);return Equality;})();module.exports = Equality;
*/
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Equality = (function () {
function Equality() {
_classCallCheck(this, Equality);
}
Equality.prototype.equals = function equals(object) {
if (object && object[this.eqDiscriminator] == this[this.eqDiscriminator]) {
return true;
}
return false;
};
Equality.prototype.equalsStrict = function equalsStrict(object) {
// override per class type
return;
};
_createClass(Equality, [{
key: "eqDiscriminator",
get: function get() {
return "id";
}
}]);
return Equality;
})();
module.exports = Equality;

@@ -1,4 +0,129 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var cpoc=require("child_process");var opus;try{opus = require("node-opus");}catch(e) { // no opus!
}var VoicePacket=require("./VoicePacket.js");var AudioEncoder=(function(){function AudioEncoder(){_classCallCheck(this,AudioEncoder);if(opus){this.opus = new opus.OpusEncoder(48000,1);}this.choice = false;}AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer){return this.opus.encode(buffer,1920);};AudioEncoder.prototype.getCommand = function getCommand(force){if(this.choice && force)return choice;var choices=["avconv","ffmpeg"];for(var _iterator=choices,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var choice=_ref;var p=cpoc.spawnSync(choice);if(!p.error){this.choice = choice;return choice;}}return "help";};AudioEncoder.prototype.encodeStream = function encodeStream(stream){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,buffer){}:arguments[1];var self=this;return new Promise(function(resolve,reject){var enc=cpoc.spawn(self.getCommand(),["-f","s16le","-ar","48000","-ac","1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af","volume=1","pipe:1","-i","-"]);stream.pipe(enc.stdin);enc.stdout.once("readable",function(){callback(null,{proc:enc,stream:enc.stdout,instream:stream});resolve({proc:enc,stream:enc.stdout,instream:stream});});enc.stdout.on("end",function(){callback("end");reject("end");});enc.stdout.on("close",function(){callback("close");reject("close");});});};AudioEncoder.prototype.encodeFile = function encodeFile(file){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,buffer){}:arguments[1];var self=this;return new Promise(function(resolve,reject){var enc=cpoc.spawn(self.getCommand(),["-f","s16le","-ar","48000","-ac","1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af","volume=1","pipe:1","-i",file]);enc.stdout.once("readable",function(){callback(null,{proc:enc,stream:enc.stdout});resolve({proc:enc,stream:enc.stdout});});enc.stdout.on("end",function(){callback("end");reject("end");});enc.stdout.on("close",function(){callback("close");reject("close");});});};return AudioEncoder;})();module.exports = AudioEncoder;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var cpoc = require("child_process");
var opus;
try {
opus = require("node-opus");
} catch (e) {
// no opus!
}
var VoicePacket = require("./VoicePacket.js");
var AudioEncoder = (function () {
function AudioEncoder() {
_classCallCheck(this, AudioEncoder);
if (opus) {
this.opus = new opus.OpusEncoder(48000, 1);
}
this.choice = false;
}
AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer) {
return this.opus.encode(buffer, 1920);
};
AudioEncoder.prototype.getCommand = function getCommand(force) {
if (this.choice && force) return choice;
var choices = ["avconv", "ffmpeg"];
for (var _iterator = choices, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var choice = _ref;
var p = cpoc.spawnSync(choice);
if (!p.error) {
this.choice = choice;
return choice;
}
}
return "help";
};
AudioEncoder.prototype.encodeStream = function encodeStream(stream) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, buffer) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
var enc = cpoc.spawn(self.getCommand(), ["-f", "s16le", "-ar", "48000", "-ac", "1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af", "volume=1", "pipe:1", "-i", "-"]);
stream.pipe(enc.stdin);
enc.stdout.once("readable", function () {
callback(null, {
proc: enc,
stream: enc.stdout,
instream: stream
});
resolve({
proc: enc,
stream: enc.stdout,
instream: stream
});
});
enc.stdout.on("end", function () {
callback("end");
reject("end");
});
enc.stdout.on("close", function () {
callback("close");
reject("close");
});
});
};
AudioEncoder.prototype.encodeFile = function encodeFile(file) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, buffer) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
var enc = cpoc.spawn(self.getCommand(), ["-f", "s16le", "-ar", "48000", "-ac", "1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af", "volume=1", "pipe:1", "-i", file]);
enc.stdout.once("readable", function () {
callback(null, {
proc: enc,
stream: enc.stdout
});
resolve({
proc: enc,
stream: enc.stdout
});
});
enc.stdout.on("end", function () {
callback("end");
reject("end");
});
enc.stdout.on("close", function () {
callback("close");
reject("close");
});
});
};
return AudioEncoder;
})();
module.exports = AudioEncoder;

@@ -1,2 +0,22 @@

"use strict"; // represents an intent of streaming music
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var EventEmitter=require("events");var StreamIntent=(function(_EventEmitter){_inherits(StreamIntent,_EventEmitter);function StreamIntent(){_classCallCheck(this,StreamIntent);_EventEmitter.call(this);}return StreamIntent;})(EventEmitter);module.exports = StreamIntent;
"use strict";
// represents an intent of streaming music
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var EventEmitter = require("events");
var StreamIntent = (function (_EventEmitter) {
_inherits(StreamIntent, _EventEmitter);
function StreamIntent() {
_classCallCheck(this, StreamIntent);
_EventEmitter.call(this);
}
return StreamIntent;
})(EventEmitter);
module.exports = StreamIntent;

@@ -1,2 +0,3 @@

"use strict"; /*
"use strict";
/*
Major credit to izy521 who is the creator of

@@ -7,6 +8,326 @@ https://github.com/izy521/discord.io,

been possible!
*/function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var WebSocket=require("ws");var dns=require("dns");var udp=require("dgram");var fs=require("fs");var AudioEncoder=require("./AudioEncoder.js");var VoicePacket=require("./VoicePacket.js");var StreamIntent=require("./StreamIntent.js");var EventEmitter=require("events");var VoiceConnection=(function(_EventEmitter){_inherits(VoiceConnection,_EventEmitter);function VoiceConnection(channel,client,session,token,server,endpoint){_classCallCheck(this,VoiceConnection);_EventEmitter.call(this);this.id = channel.id;this.voiceChannel = channel;this.client = client;this.session = session;this.token = token;this.server = server;this.endpoint = endpoint.replace(":80","");this.vWS = null; // vWS means voice websocket
this.ready = false;this.vWSData = {};this.encoder = new AudioEncoder();this.udp = null;this.playingIntent = null;this.playing = false;this.streamTime = 0;this.streamProc = null;this.KAI = null;this.init();}VoiceConnection.prototype.destroy = function destroy(){this.stopPlaying();if(this.KAI)clearInterval(this.KAI);this.vWS.close();this.udp.close();this.client.internal.sendWS({op:4,d:{guild_id:null,channel_id:null,self_mute:true,self_deaf:false}});};VoiceConnection.prototype.stopPlaying = function stopPlaying(){this.playing = false;this.playingIntent = null;if(this.instream){this.instream.end();this.instream.destroy();}};VoiceConnection.prototype.playStream = function playStream(stream){var self=this;var startTime=Date.now();var sequence=0;var time=0;var count=0;var length=20;if(self.playingIntent){self.stopPlaying();}self.playing = true;var retStream=new StreamIntent();var onWarning=false;self.playingIntent = retStream;function send(){if(!self.playingIntent || !self.playing){self.setSpeaking(false);retStream.emit("end");self;return;}try{var buffer=stream.read(1920);if(!buffer){setTimeout(send,length * 10); // give chance for some data in 200ms to appear
return;}if(buffer.length !== 1920){if(onWarning){retStream.emit("end");stream.destroy();self.setSpeaking(false);return;}else {onWarning = true;setTimeout(send,length * 10); // give chance for some data in 200ms to appear
return;}}count++;sequence + 10 < 65535?sequence += 1:sequence = 0;time + 9600 < 4294967295?time += 960:time = 0;self.sendBuffer(buffer,sequence,time,function(e){});var nextTime=startTime + count * length;self.streamTime = count * length;setTimeout(send,length + (nextTime - Date.now()));if(!self.playing)self.setSpeaking(true);retStream.emit("time",self.streamTime);}catch(e) {retStream.emit("error",e);}}self.setSpeaking(true);send();return retStream;};VoiceConnection.prototype.setSpeaking = function setSpeaking(value){this.playing = value;if(this.vWS.readyState === WebSocket.OPEN)this.vWS.send(JSON.stringify({op:5,d:{speaking:value,delay:0}}));};VoiceConnection.prototype.sendPacket = function sendPacket(packet){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;self.playing = true;try{if(self.vWS.readyState === WebSocket.OPEN)self.udp.send(packet,0,packet.length,self.vWSData.port,self.endpoint,callback);}catch(e) {self.playing = false;callback(e);return false;}};VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer,sequence,timestamp,callback){var self=this;self.playing = true;try{if(!self.encoder.opus){self.playing = false;self.emit("error","No Opus!");self.client.emit("debug","Tried to use node-opus, but opus not available - install it!");return;}var buffer=self.encoder.opusBuffer(rawbuffer);var packet=new VoicePacket(buffer,sequence,timestamp,self.vWSData.ssrc);return self.sendPacket(packet,callback);}catch(e) {self.playing = false;self.emit("error",e);return false;}};VoiceConnection.prototype.test = function test(){this.playFile("C:/users/amish/desktop/audio.mp3").then(function(stream){stream.on("time",function(time){console.log("Time",time);});});};VoiceConnection.prototype.playFile = function playFile(stream){var _this=this;var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,str){}:arguments[1];var self=this;return new Promise(function(resolve,reject){_this.encoder.encodeFile(stream)["catch"](error).then(function(data){self.streamProc = data.proc;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playRawStream = function playRawStream(stream){var _this2=this;var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,str){}:arguments[1];var self=this;return new Promise(function(resolve,reject){_this2.encoder.encodeStream(stream)["catch"](error).then(function(data){self.streamProc = data.proc;self.instream = data.instream;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.init = function init(){var _this3=this;var self=this;dns.lookup(this.endpoint,function(err,address,family){self.endpoint = address;var vWS=self.vWS = new WebSocket("wss://" + _this3.endpoint,null,{rejectUnauthorized:false});var udpClient=self.udp = udp.createSocket("udp4");var firstPacket=true;var discordIP="",discordPort="";udpClient.bind({exclusive:true});udpClient.on('message',function(msg,rinfo){var buffArr=JSON.parse(JSON.stringify(msg)).data;if(firstPacket === true){for(var i=4;i < buffArr.indexOf(0,i);i++) {discordIP += String.fromCharCode(buffArr[i]);}discordPort = msg.readUIntLE(msg.length - 2,2).toString(10);var wsDiscPayload={"op":1,"d":{"protocol":"udp","data":{"address":discordIP,"port":Number(discordPort),"mode":self.vWSData.modes[0] //Plain
}}};vWS.send(JSON.stringify(wsDiscPayload));firstPacket = false;}});vWS.on("open",function(){vWS.send(JSON.stringify({op:0,d:{server_id:self.server.id,user_id:self.client.internal.user.id,session_id:self.session,token:self.token}}));});var KAI;vWS.on("message",function(msg){var data=JSON.parse(msg);switch(data.op){case 2:self.vWSData = data.d;KAI = setInterval(function(){if(vWS && vWS.readyState === WebSocket.OPEN)vWS.send(JSON.stringify({op:3,d:null}));},data.d.heartbeat_interval);self.KAI = KAI;var udpPacket=new Buffer(70);udpPacket.writeUIntBE(data.d.ssrc,0,4);udpClient.send(udpPacket,0,udpPacket.length,data.d.port,self.endpoint,function(err){if(err)self.emit("error",err);});break;case 4:self.ready = true;self.mode = data.d.mode;self.emit("ready",self);break;}});});};return VoiceConnection;})(EventEmitter);module.exports = VoiceConnection;
*/
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WebSocket = require("ws");
var dns = require("dns");
var udp = require("dgram");
var fs = require("fs");
var AudioEncoder = require("./AudioEncoder.js");
var VoicePacket = require("./VoicePacket.js");
var StreamIntent = require("./StreamIntent.js");
var EventEmitter = require("events");
var VoiceConnection = (function (_EventEmitter) {
_inherits(VoiceConnection, _EventEmitter);
function VoiceConnection(channel, client, session, token, server, endpoint) {
_classCallCheck(this, VoiceConnection);
_EventEmitter.call(this);
this.id = channel.id;
this.voiceChannel = channel;
this.client = client;
this.session = session;
this.token = token;
this.server = server;
this.endpoint = endpoint.replace(":80", "");
this.vWS = null; // vWS means voice websocket
this.ready = false;
this.vWSData = {};
this.encoder = new AudioEncoder();
this.udp = null;
this.playingIntent = null;
this.playing = false;
this.streamTime = 0;
this.streamProc = null;
this.KAI = null;
this.init();
}
VoiceConnection.prototype.destroy = function destroy() {
this.stopPlaying();
if (this.KAI) clearInterval(this.KAI);
this.vWS.close();
this.udp.close();
this.client.internal.sendWS({
op: 4,
d: {
guild_id: null,
channel_id: null,
self_mute: true,
self_deaf: false
}
});
};
VoiceConnection.prototype.stopPlaying = function stopPlaying() {
this.playing = false;
this.playingIntent = null;
if (this.instream) {
this.instream.end();
this.instream.destroy();
}
};
VoiceConnection.prototype.playStream = function playStream(stream) {
var self = this;
var startTime = Date.now();
var sequence = 0;
var time = 0;
var count = 0;
var length = 20;
if (self.playingIntent) {
self.stopPlaying();
}
self.playing = true;
var retStream = new StreamIntent();
var onWarning = false;
self.playingIntent = retStream;
function send() {
if (!self.playingIntent || !self.playing) {
self.setSpeaking(false);
retStream.emit("end");
self;
return;
}
try {
var buffer = stream.read(1920);
if (!buffer) {
setTimeout(send, length * 10); // give chance for some data in 200ms to appear
return;
}
if (buffer.length !== 1920) {
if (onWarning) {
retStream.emit("end");
stream.destroy();
self.setSpeaking(false);
return;
} else {
onWarning = true;
setTimeout(send, length * 10); // give chance for some data in 200ms to appear
return;
}
}
count++;
sequence + 10 < 65535 ? sequence += 1 : sequence = 0;
time + 9600 < 4294967295 ? time += 960 : time = 0;
self.sendBuffer(buffer, sequence, time, function (e) {});
var nextTime = startTime + count * length;
self.streamTime = count * length;
setTimeout(send, length + (nextTime - Date.now()));
if (!self.playing) self.setSpeaking(true);
retStream.emit("time", self.streamTime);
} catch (e) {
retStream.emit("error", e);
}
}
self.setSpeaking(true);
send();
return retStream;
};
VoiceConnection.prototype.setSpeaking = function setSpeaking(value) {
this.playing = value;
if (this.vWS.readyState === WebSocket.OPEN) this.vWS.send(JSON.stringify({
op: 5,
d: {
speaking: value,
delay: 0
}
}));
};
VoiceConnection.prototype.sendPacket = function sendPacket(packet) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
self.playing = true;
try {
if (self.vWS.readyState === WebSocket.OPEN) self.udp.send(packet, 0, packet.length, self.vWSData.port, self.endpoint, callback);
} catch (e) {
self.playing = false;
callback(e);
return false;
}
};
VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer, sequence, timestamp, callback) {
var self = this;
self.playing = true;
try {
if (!self.encoder.opus) {
self.playing = false;
self.emit("error", "No Opus!");
self.client.emit("debug", "Tried to use node-opus, but opus not available - install it!");
return;
}
var buffer = self.encoder.opusBuffer(rawbuffer);
var packet = new VoicePacket(buffer, sequence, timestamp, self.vWSData.ssrc);
return self.sendPacket(packet, callback);
} catch (e) {
self.playing = false;
self.emit("error", e);
return false;
}
};
VoiceConnection.prototype.test = function test() {
this.playFile("C:/users/amish/desktop/audio.mp3").then(function (stream) {
stream.on("time", function (time) {
console.log("Time", time);
});
});
};
VoiceConnection.prototype.playFile = function playFile(stream) {
var _this = this;
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, str) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
_this.encoder.encodeFile(stream)["catch"](error).then(function (data) {
self.streamProc = data.proc;
var intent = self.playStream(data.stream);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.playRawStream = function playRawStream(stream) {
var _this2 = this;
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, str) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
_this2.encoder.encodeStream(stream)["catch"](error).then(function (data) {
self.streamProc = data.proc;
self.instream = data.instream;
var intent = self.playStream(data.stream);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.init = function init() {
var _this3 = this;
var self = this;
dns.lookup(this.endpoint, function (err, address, family) {
self.endpoint = address;
var vWS = self.vWS = new WebSocket("wss://" + _this3.endpoint, null, { rejectUnauthorized: false });
var udpClient = self.udp = udp.createSocket("udp4");
var firstPacket = true;
var discordIP = "",
discordPort = "";
udpClient.bind({ exclusive: true });
udpClient.on('message', function (msg, rinfo) {
var buffArr = JSON.parse(JSON.stringify(msg)).data;
if (firstPacket === true) {
for (var i = 4; i < buffArr.indexOf(0, i); i++) {
discordIP += String.fromCharCode(buffArr[i]);
}
discordPort = msg.readUIntLE(msg.length - 2, 2).toString(10);
var wsDiscPayload = {
"op": 1,
"d": {
"protocol": "udp",
"data": {
"address": discordIP,
"port": Number(discordPort),
"mode": self.vWSData.modes[0] //Plain
}
}
};
vWS.send(JSON.stringify(wsDiscPayload));
firstPacket = false;
}
});
vWS.on("open", function () {
vWS.send(JSON.stringify({
op: 0,
d: {
server_id: self.server.id,
user_id: self.client.internal.user.id,
session_id: self.session,
token: self.token
}
}));
});
var KAI;
vWS.on("message", function (msg) {
var data = JSON.parse(msg);
switch (data.op) {
case 2:
self.vWSData = data.d;
KAI = setInterval(function () {
if (vWS && vWS.readyState === WebSocket.OPEN) vWS.send(JSON.stringify({
op: 3,
d: null
}));
}, data.d.heartbeat_interval);
self.KAI = KAI;
var udpPacket = new Buffer(70);
udpPacket.writeUIntBE(data.d.ssrc, 0, 4);
udpClient.send(udpPacket, 0, udpPacket.length, data.d.port, self.endpoint, function (err) {
if (err) self.emit("error", err);
});
break;
case 4:
self.ready = true;
self.mode = data.d.mode;
self.emit("ready", self);
break;
}
});
});
};
return VoiceConnection;
})(EventEmitter);
module.exports = VoiceConnection;

@@ -1,1 +0,26 @@

"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var VoicePacket=function VoicePacket(data,sequence,time,ssrc){_classCallCheck(this,VoicePacket);var audioBuffer=data,returnBuffer=new Buffer(audioBuffer.length + 12);returnBuffer.fill(0);returnBuffer[0] = 0x80;returnBuffer[1] = 0x78;returnBuffer.writeUIntBE(sequence,2,2);returnBuffer.writeUIntBE(time,4,4);returnBuffer.writeUIntBE(ssrc,8,4);for(var i=0;i < audioBuffer.length;i++) {returnBuffer[i + 12] = audioBuffer[i];}return returnBuffer;};module.exports = VoicePacket;
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var VoicePacket = function VoicePacket(data, sequence, time, ssrc) {
_classCallCheck(this, VoicePacket);
var audioBuffer = data,
returnBuffer = new Buffer(audioBuffer.length + 12);
returnBuffer.fill(0);
returnBuffer[0] = 0x80;
returnBuffer[1] = 0x78;
returnBuffer.writeUIntBE(sequence, 2, 2);
returnBuffer.writeUIntBE(time, 4, 4);
returnBuffer.writeUIntBE(ssrc, 8, 4);
for (var i = 0; i < audioBuffer.length; i++) {
returnBuffer[i + 12] = audioBuffer[i];
}
return returnBuffer;
};
module.exports = VoicePacket;

2

package.json
{
"name": "discord.js",
"version": "5.0.0",
"version": "5.0.1",
"description": "A way to interface with the Discord API",

@@ -5,0 +5,0 @@ "main": "./entrypoint.js",

@@ -19,2 +19,8 @@ var Discord = require("../");

client.setAvatar(fs.readFileSync("./test/image.png"));
} else if (m.content.startsWith("startplaying")) {
var game = m.content.split(" ").slice(1).join(" ");
client.setPlayingGame(game);
} else if (m.content.startsWith("setstatus")) {
var game = m.content.split(" ").slice(1).join(" ");
client.setStatus(game);
}

@@ -21,0 +27,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc