V2 - Big update

This commit is contained in:
Mahdi Dibaiee
2015-06-29 03:12:48 +04:30
parent 4d72d21c13
commit 853145163c
34 changed files with 1323 additions and 240 deletions

49
build/api.js Normal file
View File

@ -0,0 +1,49 @@
// API methods
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _fetch = require('./fetch');
var _fetch2 = _interopRequireDefault(_fetch);
/**
* API class, has a function for each method of the Telegram API which take
* an object argument, and send request to the API server
*
* Methods: getMe, sendMessage, forwardMessage, sendPhoto, sendAudio,
* sendDocument, sendSticker, sendVideo, sendLocation, sendChatAction,
* getUserProfilePhotos, getUpdates
*/
var API =
/**
* Create a new api object with the given token
* @param {string} token
*/
function API(token) {
_classCallCheck(this, API);
this.token = token;
};
exports['default'] = API;
API.prototype.request = function request(method, data) {
return (0, _fetch2['default'])(this.token + '/' + method, data);
};
var methods = ['getMe', 'sendMessage', 'forwardMessage', 'sendPhoto', 'sendAudio', 'sendDocument', 'sendSticker', 'sendVideo', 'sendLocation', 'sendChatAction', 'getUserProfilePhotos', 'getUpdates'];
methods.forEach(function (method) {
API.prototype[method] = function (data) {
return this.request(method, data);
};
});
module.exports = exports['default'];

53
build/fetch.js Normal file
View File

@ -0,0 +1,53 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = fetch;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _https = require('https');
var _https2 = _interopRequireDefault(_https);
var _qs = require('qs');
var _qs2 = _interopRequireDefault(_qs);
function fetch(path, data) {
var post = _qs2['default'].stringify(data);
return new Promise(function (resolve, reject) {
var res = '';
var req = _https2['default'].request({
hostname: 'api.telegram.org',
method: data ? 'POST' : 'GET',
path: '/bot' + path,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, function (response) {
response.on('data', function (chunk) {
res += chunk;
});
response.on('end', function () {
try {
var json = JSON.parse(res);
resolve(json);
} catch (e) {
reject(e);
}
});
}).on('error', reject);
if (post) {
req.write(post);
}
req.end();
});
}
module.exports = exports['default'];

184
build/index.js Normal file
View File

@ -0,0 +1,184 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; }; })();
var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
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) subClass.__proto__ = superClass; }
require('babel/polyfill');
var _api = require('./api');
var _api2 = _interopRequireDefault(_api);
var _events = require('events');
var DEFAULTS = {
update: {
offset: 0,
timeout: 0.5,
limit: 100
}
};
/**
* Bot class used to connect to a new bot
* Bots have an api property which gives access to all Telegram API methods,
* see API class
*/
var Bot = (function (_EventEmitter) {
/**
* Create and connect to a new bot
* @param {object} options Bot properties.
*/
function Bot() {
var options = arguments[0] === undefined ? { update: {} } : arguments[0];
_classCallCheck(this, Bot);
_get(Object.getPrototypeOf(Bot.prototype), 'constructor', this).call(this);
if (!options.token) {
throw new Error('Token cannot be empty');
}
this.token = options.token;
this.update = Object.assign(options.update || {}, DEFAULTS.update);
this.api = new _api2['default'](this.token);
this.msg = {};
// EventEmitter
this._events = {};
this._userEvents = [];
}
_inherits(Bot, _EventEmitter);
_createClass(Bot, [{
key: 'start',
/**
* Gets information about the bot and then starts polling updates from API
* Emits an `update` event after polling with the response from server
* Returns a promise which is resolved after the bot information is received
* and set to it's `info` property i.e. bot.info
* @return {promise} A promise which is resolved with the response of getMe
*/
value: function start() {
var _this2 = this;
var poll = (function () {
var _this = this;
this.api.getUpdates(this.update).then(function (response) {
setTimeout(poll, _this.update.timeout * 1000);
var result = response.result;
if (!result.length) {
return;
}
if (!_this.update.offset) {
var updateId = result[result.length - 1].update_id;
_this.update.offset = updateId;
}
if (_this.update) {
_this.update.offset += 1;
}
_this.emit('update', response.result);
result.forEach(function (res) {
var text = res.message.text;
if (text.startsWith('/')) {
// Commands are sent in /command@botusername format in groups
var regex = new RegExp('@' + _this.info.username + '$');
text = text.replace(regex, '');
}
var ev = _this._userEvents.find(function (_ref) {
var pattern = _ref.pattern;
return pattern.test(text);
});
ev.listener(res);
});
});
}).bind(this);
return this.api.getMe().then(function (response) {
_this2.info = response.result;
poll();
});
}
}, {
key: 'get',
/**
* Listens on specific message matching the pattern which can be an string
* or a regexp.
* @param {string/regex} pattern
* @param {function} listener function to call when a message matching the
* pattern is found, gets the Update
* In case of string, the message should start
* with the string i.e. /^yourString/
* @return {object} returns the bot object
*/
value: function get(pattern, listener) {
if (typeof pattern === 'string') {
pattern = new RegExp('^' + pattern);
}
this._userEvents.push({
pattern: pattern, listener: listener
});
return this;
}
}, {
key: 'command',
/**
* Listens on a command
* @param {string} cmd the command string, should not include slash (/)
* @param {function} listener function to call when the command is received,
* gets the update
* @return {object} returns the bot object
*/
value: function command(cmd, listener) {
this._userEvents.push({
pattern: new RegExp('/' + cmd),
listener: listener
});
return this;
}
}, {
key: 'send',
/**
* Sends the message provided
* @param {object} message The message to send. Gets it's send method called
* @return {unknown} returns the result of calling message's send method
*/
value: function send(message) {
return message.send(this);
}
}]);
return Bot;
})(_events.EventEmitter);
exports['default'] = Bot;
module.exports = exports['default'];

66
build/types/Base.js Normal file
View File

@ -0,0 +1,66 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; }; })();
var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
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) subClass.__proto__ = superClass; }
var _events = require('events');
/**
* Base class of all classes
*/
var Base = (function (_EventEmitter) {
function Base() {
_classCallCheck(this, Base);
_get(Object.getPrototypeOf(Base.prototype), 'constructor', this).call(this);
this.properties = {};
}
_inherits(Base, _EventEmitter);
_createClass(Base, [{
key: 'getProperties',
/**
* Returns properties of the object
* @return {object} properties of object
*/
value: function getProperties() {
return this.properties;
}
}, {
key: 'setProperties',
/**
* Set properties of the object
* @param {object} object properties to set
* @param {boolean} extend A boolean indicating if the properties should be
* extended by the object provided (Object.assign)
* or properties should be replaced by the object
* defaults to true
* @return {object} returns the properties (same as getProperties)
*/
value: function setProperties(object) {
var extend = arguments[1] === undefined ? true : arguments[1];
this.properties = extend ? Object.assign(this.properties, object) : object;
return this.getProperties();
}
}]);
return Base;
})(_events.EventEmitter);
exports['default'] = Base;
module.exports = exports['default'];

138
build/types/Keyboard.js Normal file
View File

@ -0,0 +1,138 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; }; })();
var _get = function get(_x6, _x7, _x8) { var _again = true; _function: while (_again) { var object = _x6, property = _x7, receiver = _x8; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x6 = parent; _x7 = property; _x8 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
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) subClass.__proto__ = superClass; }
var _Base2 = require('./Base');
var _Base3 = _interopRequireDefault(_Base2);
/**
* Keyboard class, used to configure keyboards for messages.
* You should pass your instance of this class to message.keyboard() method
*/
var Keyboard = (function (_Base) {
/**
* Create a new keyboard
* @param {object} properties Keyboard properties, as defined by Telegram API
* See ReplyKeyboardMarkup, ReplyKeyboardHide,
* ForceReply
*/
function Keyboard() {
var properties = arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Keyboard);
_get(Object.getPrototypeOf(Keyboard.prototype), 'constructor', this).call(this);
this.properties = properties;
}
_inherits(Keyboard, _Base);
_createClass(Keyboard, [{
key: 'keys',
/**
* Set the keyboard property of reply_markup
* @param {array} keys An array of arrays, with the format of
* Column Column
* Row [['TopLeft', 'TopRight'],
* Row ['BottomLeft', 'BottomRight']]
* @return {object} returns the keyboard object
*/
value: function keys(_keys) {
this.properties.keyboard = _keys;
this.properties.hide_keyboard = false;
return this;
}
}, {
key: 'force',
/**
* Set force_keyboard property of reply_markup
* @param {boolean} enable value of force_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
value: function force() {
var enable = arguments[0] === undefined ? true : arguments[0];
this.properties.force_keyboard = enable;
return this;
}
}, {
key: 'resize',
/**
* Set resize_keyboard property of reply_markup
* @param {boolean} enable value of resize_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
value: function resize() {
var enable = arguments[0] === undefined ? true : arguments[0];
this.properties.resize_keyboard = enable;
return this;
}
}, {
key: 'oneTime',
/**
* Set force_keyboard property of reply_markup
* @param {boolean} enable value of force_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
value: function oneTime() {
var enable = arguments[0] === undefined ? true : arguments[0];
this.properties.one_time_keyboard = enable;
return this;
}
}, {
key: 'selective',
/**
* Set selective property of reply_markup
* @param {boolean} enable value of force_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
value: function selective() {
var enable = arguments[0] === undefined ? true : arguments[0];
this.properties.selective = enable;
return this;
}
}, {
key: 'hide',
/**
* Set hide_keyboard property of reply_markup to true
* @return {object} returns the keyboard object
*/
value: function hide() {
this.properties = {
hide_keyboard: true
};
return this;
}
}]);
return Keyboard;
})(_Base3['default']);
exports['default'] = Keyboard;
module.exports = exports['default'];

156
build/types/Message.js Normal file
View File

@ -0,0 +1,156 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; }; })();
var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
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) subClass.__proto__ = superClass; }
var _Base2 = require('./Base');
var _Base3 = _interopRequireDefault(_Base2);
/**
* Message class, used to send message to a chat
*/
var Message = (function (_Base) {
/**
* Create a new message
* @param {object} properties Message properties, as defined by Telegram API
*/
function Message() {
var properties = arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Message);
_get(Object.getPrototypeOf(Message.prototype), 'constructor', this).call(this);
this.properties = properties;
this._keyboard = new _Base3['default']();
}
_inherits(Message, _Base);
_createClass(Message, [{
key: 'to',
/**
* Set chat_id of the message
* @param {number} chat
* @return {object} returns the message object
*/
value: function to(chat) {
this.properties.chat_id = chat;
return this;
}
}, {
key: 'text',
/**
* Set text of the message
* @param {string} text Message's content
* @return {object} returns the message object
*/
value: function text(_text) {
this.properties.text = _text;
return this;
}
}, {
key: 'reply',
/**
* Set reply_to_message_id of the message
* @param {number} id message_id of the message to reply to
* @return {object} returns the message object
*/
value: function reply(id) {
this.properties.reply_to_message_id = id;
return this;
}
}, {
key: 'keyboard',
/**
* Sets keyboard of the message
* The value of reply_markup is set to the sanitized keyboard properties
* i.e. reply_markup = JSON.stringify(kb.getProperties())
* @param {object} kb A Keyboard instance
* @return {object} returns the message object
*/
value: function keyboard(kb) {
this._keyboard = kb;
return this;
}
}, {
key: 'send',
/**
* Sends the message, you should only use this method yourself if
* you are extending this class. Normally you should call bot.send(message)
*
* Events: message:sent => Emitted after sending the message to API, gets the
* API's response
*
* message:answer => Emitted when your message gets an answer from
* the contact (reply in case of groups)
* gets the Update object containing message
*
* @param {object} bot
* @return {promise} returns a promise, resolved with message:answer
*/
value: function send(bot) {
var _this = this;
var messageId = undefined;
var reply_markup = JSON.stringify(this._keyboard.getProperties());
this.properties.reply_markup = reply_markup;
return new Promise(function (resolve) {
bot.api.sendMessage(_this.properties).then(function (response) {
messageId = response.result.message_id;
_this.emit('message:sent', response);
});
if (_this._keyboard.one_time_keyboard) {
_this._keyboard.replyMarkup = '';
}
var chat = _this.properties.chat_id;
bot.on('update', function listener(result) {
var update = result.find(function (_ref) {
var message = _ref.message;
// if in a group, there will be a reply to this message
if (chat < 0) {
return message.chat.id === chat && message.reply_to_message.message_id === messageId;
} else {
return message.chat.id === chat;
}
});
if (update) {
resolve(update);
this.emit('message:answer', update);
bot.removeListener('update', listener);
}
});
});
}
}]);
return Message;
})(_Base3['default']);
exports['default'] = Message;
module.exports = exports['default'];

112
build/types/Question.js Normal file
View File

@ -0,0 +1,112 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; }; })();
var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
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) subClass.__proto__ = superClass; }
var _Message2 = require('./Message');
var _Message3 = _interopRequireDefault(_Message2);
var _Keyboard = require('./Keyboard');
var _Keyboard2 = _interopRequireDefault(_Keyboard);
/**
* Question class, extends Message
* Sends a message, shows a keyboard with the answers provided, and validates
* the answer
*/
var Question = (function (_Message) {
/**
* Create a new question
* @param {object} options Options, same as Message, plus `answers` which
* is a keyboard layout, see Keyboard#keys
*/
function Question() {
var options = arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Question);
_get(Object.getPrototypeOf(Question.prototype), 'constructor', this).call(this, options);
var kb = new _Keyboard2['default']().force().oneTime().selective().keys(this.properties.answers);
this.keyboard(kb);
}
_inherits(Question, _Message);
_createClass(Question, [{
key: 'answers',
/**
* Sets answers of the question. This is passed to Keyboard#keys, and then
* used to validate the answer given
* @param {array} answers Array of arrays of strings, same as Keyboard#keys
* @return {object} returns the question object
*/
value: function answers(_answers) {
this.answers = _answers;
this._keyboard.keys(_answers);
return this;
}
}, {
key: 'send',
/**
* Sends the question (same as Message#send), and validates the answer given
* if the answer is one of the defined answers, resolves, else rejects
* You should not manually use this method unless you're extending this class
* You should instead use bot.send(question);
* @param {object} bot
* @return {promise} A promise which is resolved in case of valid answer, and
* rejected in case of invalid answer
*/
value: function send(bot) {
var _this = this;
var answers = this.answers;
return new Promise(function (resolve, reject) {
_get(Object.getPrototypeOf(Question.prototype), 'send', _this).call(_this, bot).then(function (update) {
var message = update.message;
var answer = undefined;
answers.forEach(function find(a) {
if (Array.isArray(a)) {
a.forEach(find);
}
if (a === message.text) {
answer = a;
}
});
if (answer) {
resolve(answer, update);
_this.emit('question:answer', answer, update);
} else {
reject(update);
_this.emit('question:invalid', update);
}
});
});
}
}]);
return Question;
})(_Message3['default']);
exports['default'] = Question;
module.exports = exports['default'];

1
build/utils.js Normal file
View File

@ -0,0 +1 @@
"use strict";