Merge pull request #52 from abalabahaha/rewrite

Typing and setting status, various bug fixes
This commit is contained in:
Amish Shah
2015-11-17 18:54:14 +00:00
28 changed files with 293 additions and 54 deletions

View File

@@ -1,7 +1,7 @@
/* /*
this bot is a ping pong bot, and every time a message this bot is a ping pong bot, and every time a message
beginning with "ping" is sent, it will reply with beginning with "ping" is sent, it will reply with
"pong". "pong!".
*/ */
var Discord = require("../"); var Discord = require("../");
@@ -11,26 +11,29 @@ var AuthDetails = require("./auth.json");
var bot = new Discord.Client(); var bot = new Discord.Client();
//when the bot is ready
bot.on("ready", function () { bot.on("ready", function () {
console.log("Ready to begin! Serving in " + bot.channels.length + " channels"); console.log("Ready to begin! Serving in " + bot.channels.length + " channels");
}); });
//when the bot disconnects
bot.on("disconnected", function () { bot.on("disconnected", function () {
//alert the console
console.log("Disconnected!"); console.log("Disconnected!");
process.exit(1); //exit node.js with an error
//exit node.js with an error
process.exit(1);
}); });
//when the bot receives a message
bot.on("message", function (msg) { bot.on("message", function (msg) {
if (msg.content.substring(0, 4) === "ping") { //if message begins with "ping"
if (msg.content.indexOf("ping") === 0) {
//send a message to the channel the ping message was sent in. //send a message to the channel the ping message was sent in.
bot.sendMessage(msg.channel, "pong!"); bot.sendMessage(msg.channel, "pong!");
//alert the console
console.log("pong-ed " + msg.sender.username);
//alert the console
console.log("pong-ed " + msg.author.username);
} }
}); });

View File

@@ -8,13 +8,13 @@ module.exports = function (grunt) {
babel: { babel: {
options: { options: {
loose: "all", loose: "all",
compact: true compact: !grunt.option('dev')
}, },
dist: { dist: {
files: [{ files: [{
expand: true, expand: true,
cwd: "src/", cwd: "src/",
src: ["/**/**.*"], src: ["**/**.*"],
dest: "lib/", dest: "lib/",
ext: ".js" ext: ".js"
}] }]

View File

@@ -509,6 +509,49 @@ var Client = (function (_EventEmitter) {
}); });
}; };
//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 // def setTopic
Client.prototype.setTopic = function setTopic(channel, topic) { Client.prototype.setTopic = function setTopic(channel, topic) {
@@ -624,9 +667,19 @@ var Client = (function (_EventEmitter) {
get: function get() { get: function get() {
return this.internal.voiceConnection; return this.internal.voiceConnection;
} }
}, {
key: "readyTime",
get: function get() {
return this.internal.readyTime;
}
}, {
key: "uptime",
get: function get() {
return this.internal.uptime;
}
}]); }]);
return Client; return Client;
})(EventEmitter); })(EventEmitter);
module.exports = Client; module.exports = Client;

View File

@@ -4,4 +4,4 @@ exports.IDLE = 0;
exports.LOGGING_IN = 1; exports.LOGGING_IN = 1;
exports.LOGGED_IN = 2; exports.LOGGED_IN = 2;
exports.READY = 3; exports.READY = 3;
exports.DISCONNECTED = 4; exports.DISCONNECTED = 4;

View File

@@ -1,5 +1,7 @@
"use strict"; "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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var EventEmitter = require("events"); var EventEmitter = require("events");
@@ -46,6 +48,7 @@ var InternalClient = (function () {
this.private_channels = new Cache(); this.private_channels = new Cache();
this.voiceConnection = null; this.voiceConnection = null;
this.resolver = new Resolver(this); this.resolver = new Resolver(this);
this.readyTime = null;
} }
//def leaveVoiceChannel //def leaveVoiceChannel
@@ -856,6 +859,54 @@ var InternalClient = (function () {
}); });
}; };
//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 setTopic //def setTopic
InternalClient.prototype.setTopic = function setTopic(chann) { InternalClient.prototype.setTopic = function setTopic(chann) {
@@ -870,7 +921,7 @@ var InternalClient = (function () {
request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({ request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({
name: channel.name, name: channel.name,
position: 0, position: channel.position,
topic: topic topic: topic
}).end(function (err, res) { }).end(function (err, res) {
if (err) { if (err) {
@@ -898,7 +949,7 @@ var InternalClient = (function () {
request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({ request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({
name: name, name: name,
position: 0, position: channel.position,
topic: channel.topic topic: channel.topic
}).end(function (err, res) { }).end(function (err, res) {
if (err) { if (err) {
@@ -927,7 +978,7 @@ var InternalClient = (function () {
request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({ request.patch(Endpoints.CHANNEL(channel.id)).set("authorization", self.token).send({
name: name, name: name,
position: 0, position: channel.position,
topic: topic topic: topic
}).end(function (err, res) { }).end(function (err, res) {
if (err) { if (err) {
@@ -1008,6 +1059,10 @@ var InternalClient = (function () {
client.emit("disconnected"); client.emit("disconnected");
}; };
this.websocket.onerror = function (e) {
console.log(e);
};
this.websocket.onmessage = function (e) { this.websocket.onmessage = function (e) {
if (e.type === "Binary") { if (e.type === "Binary") {
@@ -1046,6 +1101,8 @@ var InternalClient = (function () {
client.emit("ready"); client.emit("ready");
client.emit("debug", "ready packet took " + (Date.now() - startTime) + "ms to process"); 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."); client.emit("debug", "ready with " + self.servers.length + " servers, " + self.channels.length + " channels and " + self.users.length + " users cached.");
self.readyTime = Date.now();
break; break;
case PacketType.MESSAGE_CREATE: case PacketType.MESSAGE_CREATE:
@@ -1392,7 +1449,14 @@ var InternalClient = (function () {
}; };
}; };
_createClass(InternalClient, [{
key: "uptime",
get: function get() {
return this.readyTime ? Date.now() - this.readyTime : null;
}
}]);
return InternalClient; return InternalClient;
})(); })();
module.exports = InternalClient; module.exports = InternalClient;

View File

@@ -182,4 +182,4 @@ var Resolver = (function () {
return Resolver; return Resolver;
})(); })();
module.exports = Resolver; module.exports = Resolver;

View File

@@ -124,4 +124,4 @@ var PacketType = {
exports.API_ENDPOINT = API; exports.API_ENDPOINT = API;
exports.Endpoints = Endpoints; exports.Endpoints = Endpoints;
exports.PacketType = PacketType; exports.PacketType = PacketType;
exports.Permissions = Permissions; exports.Permissions = Permissions;

View File

@@ -27,4 +27,4 @@ var Channel = (function (_Equality) {
return Channel; return Channel;
})(Equality); })(Equality);
module.exports = Channel; module.exports = Channel;

View File

@@ -72,4 +72,4 @@ var ChannelPermissions = (function () {
return ChannelPermissions; return ChannelPermissions;
})(); })();
module.exports = ChannelPermissions; module.exports = ChannelPermissions;

View File

@@ -60,4 +60,4 @@ var Message = (function () {
return Message; return Message;
})(); })();
module.exports = Message; module.exports = Message;

View File

@@ -52,4 +52,4 @@ var PMChannel = (function (_Equality) {
return PMChannel; return PMChannel;
})(Equality); })(Equality);
module.exports = PMChannel; module.exports = PMChannel;

View File

@@ -83,4 +83,4 @@ var PermissionOverwrite = (function () {
return PermissionOverwrite; return PermissionOverwrite;
})(); })();
module.exports = PermissionOverwrite; module.exports = PermissionOverwrite;

View File

@@ -136,4 +136,4 @@ var Role = (function () {
return Role; return Role;
})(); })();
module.exports = Role; module.exports = Role;

View File

@@ -166,4 +166,4 @@ var Server = (function (_Equality) {
return Server; return Server;
})(Equality); })(Equality);
module.exports = Server; module.exports = Server;

View File

@@ -21,6 +21,7 @@ var ServerChannel = (function (_Channel) {
_Channel.call(this, data, client); _Channel.call(this, data, client);
this.name = data.name; this.name = data.name;
this.type = data.type; this.type = data.type;
this.position = data.position;
this.permissionOverwrites = new Cache(); this.permissionOverwrites = new Cache();
this.server = server; this.server = server;
data.permission_overwrites.forEach(function (permission) { data.permission_overwrites.forEach(function (permission) {
@@ -109,4 +110,4 @@ var ServerChannel = (function (_Channel) {
return ServerChannel; return ServerChannel;
})(Channel); })(Channel);
module.exports = ServerChannel; module.exports = ServerChannel;

View File

@@ -57,4 +57,4 @@ var TextChannel = (function (_ServerChannel) {
return TextChannel; return TextChannel;
})(ServerChannel); })(ServerChannel);
module.exports = TextChannel; module.exports = TextChannel;

View File

@@ -55,4 +55,4 @@ var User = (function (_Equality) {
return User; return User;
})(Equality); })(Equality);
module.exports = User; module.exports = User;

View File

@@ -18,4 +18,4 @@ var VoiceChannel = (function (_ServerChannel) {
return VoiceChannel; return VoiceChannel;
})(ServerChannel); })(ServerChannel);
module.exports = VoiceChannel; module.exports = VoiceChannel;

View File

@@ -95,4 +95,4 @@ var Cache = (function (_Array) {
return Cache; return Cache;
})(Array); })(Array);
module.exports = Cache; module.exports = Cache;

View File

@@ -42,4 +42,4 @@ var Equality = (function () {
return Equality; return Equality;
})(); })();
module.exports = Equality; module.exports = Equality;

View File

@@ -126,4 +126,4 @@ var AudioEncoder = (function () {
return AudioEncoder; return AudioEncoder;
})(); })();
module.exports = AudioEncoder; module.exports = AudioEncoder;

View File

@@ -19,4 +19,4 @@ var StreamIntent = (function (_EventEmitter) {
return StreamIntent; return StreamIntent;
})(EventEmitter); })(EventEmitter);
module.exports = StreamIntent; module.exports = StreamIntent;

View File

@@ -329,4 +329,4 @@ var VoiceConnection = (function (_EventEmitter) {
return VoiceConnection; return VoiceConnection;
})(EventEmitter); })(EventEmitter);
module.exports = VoiceConnection; module.exports = VoiceConnection;

View File

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

View File

@@ -14,4 +14,4 @@ module.exports = {
TextChannel: require("./Structures/TextChannel"), TextChannel: require("./Structures/TextChannel"),
User: require("./Structures/User"), User: require("./Structures/User"),
VoiceChannel: require("./Structures/VoiceChannel") VoiceChannel: require("./Structures/VoiceChannel")
}; };

View File

@@ -29,11 +29,19 @@ class Client extends EventEmitter {
get privateChannels(){ get privateChannels(){
return this.internal.private_channels; return this.internal.private_channels;
} }
get voiceConnection(){ get voiceConnection(){
return this.internal.voiceConnection; return this.internal.voiceConnection;
} }
get readyTime(){
return this.internal.readyTime;
}
get uptime(){
return this.internal.uptime;
}
// def login // def login
login(email, password, cb = function (err, token) { }) { login(email, password, cb = function (err, token) { }) {
var self = this; var self = this;
@@ -497,6 +505,50 @@ class Client extends EventEmitter {
}); });
} }
//def setStatus
setStatus(idleStatus, gameID, callback=function(err){}){
var self = this;
return new Promise((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(() => {
callback();
resolve();
})
.catch(e => {
callback(e);
reject(e);
});
})
}
//def sendTyping
sendTyping(channel, callback=function(err){}){
var self = this;
return new Promise((resolve, reject) => {
self.internal.sendTyping(channel)
.then(() => {
callback();
resolve();
})
.catch(e => {
callback(e);
reject(e);
});
})
}
// def setTopic // def setTopic
setTopic(channel, topic, callback=function(err){}){ setTopic(channel, topic, callback=function(err){}){
var self = this; var self = this;

View File

@@ -42,6 +42,11 @@ class InternalClient {
this.private_channels = new Cache(); this.private_channels = new Cache();
this.voiceConnection = null; this.voiceConnection = null;
this.resolver = new Resolver(this); this.resolver = new Resolver(this);
this.readyTime = null;
}
get uptime() {
return (this.readyTime ? Date.now() - this.readyTime : null);
} }
//def leaveVoiceChannel //def leaveVoiceChannel
@@ -699,6 +704,7 @@ class InternalClient {
}); });
} }
// def deleteRole // def deleteRole
deleteRole(role) { deleteRole(role) {
var self = this; var self = this;
@@ -910,6 +916,57 @@ class InternalClient {
}); });
} }
//def setStatus
setStatus(idleStatus, gameID) {
var self = this;
return new Promise((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
sendTyping(channel) {
var self = this;
return new Promise((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((err, res) => {
if (err) {
reject(err);
} else {
resolve();
}
})
}
});
}
//def setTopic //def setTopic
setTopic(chann, topic = "") { setTopic(chann, topic = "") {
var self = this; var self = this;
@@ -924,7 +981,7 @@ class InternalClient {
.set("authorization", self.token) .set("authorization", self.token)
.send({ .send({
name: channel.name, name: channel.name,
position: 0, position: channel.position,
topic: topic topic: topic
}) })
.end((err, res) => { .end((err, res) => {
@@ -940,6 +997,7 @@ class InternalClient {
}); });
} }
//def setChannelName //def setChannelName
setChannelName(chann, name = "discordjs_is_the_best") { setChannelName(chann, name = "discordjs_is_the_best") {
var self = this; var self = this;
@@ -954,7 +1012,7 @@ class InternalClient {
.set("authorization", self.token) .set("authorization", self.token)
.send({ .send({
name: name, name: name,
position: 0, position: channel.position,
topic: channel.topic topic: channel.topic
}) })
.end((err, res) => { .end((err, res) => {
@@ -970,6 +1028,7 @@ class InternalClient {
}); });
} }
//def setChannelNameAndTopic //def setChannelNameAndTopic
setChannelNameAndTopic(chann, name = "discordjs_is_the_best", topic = "") { setChannelNameAndTopic(chann, name = "discordjs_is_the_best", topic = "") {
var self = this; var self = this;
@@ -984,7 +1043,7 @@ class InternalClient {
.set("authorization", self.token) .set("authorization", self.token)
.send({ .send({
name: name, name: name,
position: 0, position: channel.position,
topic: topic topic: topic
}) })
.end((err, res) => { .end((err, res) => {
@@ -1073,6 +1132,10 @@ class InternalClient {
client.emit("disconnected"); client.emit("disconnected");
} }
this.websocket.onerror = (e) => {
console.log(e);
}
this.websocket.onmessage = (e) => { this.websocket.onmessage = (e) => {
if (e.type === "Binary") { if (e.type === "Binary") {
@@ -1109,6 +1172,8 @@ class InternalClient {
client.emit("ready"); client.emit("ready");
client.emit("debug", `ready packet took ${Date.now() - startTime}ms to process`); 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.`); client.emit("debug", `ready with ${self.servers.length} servers, ${self.channels.length} channels and ${self.users.length} users cached.`);
self.readyTime = Date.now();
break; break;
case PacketType.MESSAGE_CREATE: case PacketType.MESSAGE_CREATE:

View File

@@ -11,6 +11,7 @@ class ServerChannel extends Channel{
super(data, client); super(data, client);
this.name = data.name; this.name = data.name;
this.type = data.type; this.type = data.type;
this.position = data.position;
this.permissionOverwrites = new Cache(); this.permissionOverwrites = new Cache();
this.server = server; this.server = server;
data.permission_overwrites.forEach((permission) => { data.permission_overwrites.forEach((permission) => {