refactor: remove grunt and babel

remove grunt from dependencies, and use transformed code instead using babel/register.
change API a litte
This commit is contained in:
Ali Movahedi
2016-03-28 00:59:00 +04:30
parent 8e14a026df
commit e5c25bd9c1
44 changed files with 576 additions and 1446 deletions

35
src/functions/api.js Normal file
View File

@ -0,0 +1,35 @@
// API methods
import fetch from './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
*/
export default class API {
/**
* Create a new api object with the given token
* @param {string} token
*/
constructor(token) {
this.token = token;
}
}
API.prototype.request = function request(method, data) {
return fetch(this.token + '/' + method, data);
};
const methods = ['getMe', 'sendMessage', 'forwardMessage', 'sendPhoto',
'sendAudio', 'sendDocument', 'sendSticker', 'sendVideo',
'sendLocation', 'sendChatAction', 'getUserProfilePhotos',
'getUpdates', 'setWebhook'];
methods.forEach(method => {
API.prototype[method] = function(data) {
return this.request(method, data);
};
});

View File

@ -0,0 +1,110 @@
const FORMAT_REQUIRED = /<(\W*)(\w+)\|?(\w+)?>/g;
const FORMAT_OPTIONAL = /\[(\W*)(\w+)\|?(\w+)?\]/g;
const FORMAT_REST = /\.{3}(\w+)/g;
const ESCAPABLE = '.^$*+?()[{\\|}]'.split('');
const REQUIRED = 0;
const OPTIONAL = 1;
const REST = 2;
/**
* Parses a message for arguments, based on format
*
* The format option may include '<requiredParam>' and '[optionalParam]' and
* '...[restParam]'
* <requiredParam> indicates a required, single-word argument
* [optionalParam] indicates an optinal, single-word argument
* ...[restParam] indicates a multi-word argument which records until end
*
* You can define a type for your arguments using pipe | sign, like this:
* [count|number]
* Supported Types are: number and word, defaults to word
*
* Example:
* format: '<name> [count|number] ...text'
* string 1: 'Someone Hey, wassup'
* {name: 'Someone',
* count: undefined,
* text: 'Hey, wassup'}
*
* string 2: 'Someone 5 Hey, wassup'
* {name: 'Someone',
* count: 5,
* text: 'Hey, wassup'}
* @param {string} format Format, as described above
* @param {string} string The message to parse
* @return {object} Parsed arguments
*/
export default function argumentParser(format, string) {
string = string.replace(/[^\s]+/, '').trim();
format = format.replace(/[^\s]+/, '').trim();
if (!format) return {args: {}, params: {}};
let indexes = [],
params = {};
format = format.replace(/\s/g, '\\s*');
format = format.replace(FORMAT_REQUIRED,
(f, symbols, arg, type = 'word', offset) => {
indexes.push({arg, offset});
params[arg] = REQUIRED;
return (escape(symbols) + getFormat(type, 'required')).trim();
});
format = format.replace(FORMAT_OPTIONAL,
(f, symbols, arg, type = 'word', offset) => {
indexes.push({arg, offset});
params[arg] = OPTIONAL;
return (escape(symbols, '?') + getFormat(type, 'optional')).trim();
});
format = format.replace(FORMAT_REST, (full, arg, offset) => {
indexes.push({offset, arg});
params[arg] = REST;
return getFormat(null, 'rest');
});
if (!string) return {args: {}, params};
indexes = indexes.sort((a, b) => {
return a.offset < b.offset ? -1 : 1;
});
const regex = new RegExp(format);
const matched = regex.exec(string).slice(1);
const object = {};
for (let [index, match] of matched.entries()) {
const argument = indexes[index];
object[argument.arg] = match;
}
return {args: object, params};
}
function escape(symbols, append = '') {
return symbols.split('').map(symbol => {
return (ESCAPABLE.indexOf(symbol) ? `\\${symbol}` : symbol) + append;
}).join('');
}
const TYPES = {
'number': '\\d',
'word': '\\S'
};
function getFormat(type = 'word', param = 'required') {
const t = TYPES[type];
switch (param) {
case 'required':
return `(${t}+)`;
case 'optional':
return `(${t}+)?`;
case 'rest':
return `(.*)`;
}
}

42
src/functions/fetch.js Normal file
View File

@ -0,0 +1,42 @@
import unirest from 'unirest';
export default function fetch(path, data = {}) {
return new Promise((resolve, reject) => {
const files = {};
for (let key of Object.keys(data)) {
if (data[key].file) {
files[key] = data[key].file;
delete data[key];
}
}
unirest.post('https://api.telegram.org/bot' + path)
.field(data)
.attach(files)
.end(response => {
if (response.statusType === 4 || response.statusType === 5 ||
!response.body || !response.body.ok) {
reject(response);
} else {
resolve(response.body);
}
});
});
}
export function getBody(stream) {
let data = '';
return new Promise((resolve, reject) => {
stream.on('data', chunk => {
data += chunk;
});
stream.on('end', () => {
resolve(data);
});
stream.on('error', reject);
});
}

11
src/functions/poll.js Normal file
View File

@ -0,0 +1,11 @@
export default function poll(bot) {
return bot.api.getUpdates(bot.update).then(response => {
if (!response.result.length) {
return poll(bot);
}
bot.emit('update', response.result);
if (bot._stop) return null;
return poll(bot);
});
}

24
src/functions/webhook.js Normal file
View File

@ -0,0 +1,24 @@
import https from 'http';
import qs from 'qs';
import {getBody} from './fetch';
const DEFAULTS = {
server: {},
port: 443
};
export default function webhook(options = {}, bot) {
options = Object.assign(DEFAULTS, options);
return bot.api.setWebhook(options.url).then(() => {
bot._webhookServer = https.createServer(options.server, (req, res) => {
return getBody(req).then(data => {
bot.emit('update', qs.parse(data).result);
res.end('OK');
});
}).listen(options.port);
});
}

243
src/index.js Normal file
View File

@ -0,0 +1,243 @@
import 'babel-polyfill';
import API from './functions/api';
import webhook from './functions/webhook';
import poll from './functions/poll';
import argumentParser from './functions/argument-parser';
import {EventEmitter} from 'events';
import Message from './types/Message';
import File from './types/File';
import Keyboard from './types/Keyboard';
import BulkMessage from './types/BulkMessage';
import Question from './types/Question';
import Forward from './types/Forward';
const DEFAULTS = {
update: {
offset: 0,
timeout: 20,
limit: 100
}
};
const REQUIRED = 0;
console.log(poll);
/**
* 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
*/
export default class Bot extends EventEmitter {
/**
* Create and connect to a new bot
* @param {object} options Bot properties.
*/
constructor(options = {update: {}}) {
super();
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 API(this.token);
this.msg = {};
// EventEmitter
this._events = {};
this._userEvents = [];
this.setMaxListeners(100);
}
/**
* Gets information about the bot and then
* 1) starts polling updates from API
* 2) sets a webhook as defined by the first parameter and listens for updates
* 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
*
* @param {object} hook An object containg options passed to webhook
* properties:
* - url: HTTPS url to listen on POST requests coming
* from the Telegram API
* - port: the port to listen to, defaults to 443
* - server: An object passed to https.createServer
*
* @return {promise} A promise which is resolved with the response of getMe
*/
start(hook) {
if (hook) {
return webhook(hook, this);
}
return this.api.getMe().then(response => {
this.info = response.result;
this.on('update', this._update);
if (hook) {
return webhook(hook, this);
} else {
return poll(this);
}
});
}
/**
* 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
*/
get(pattern, listener) {
if (typeof pattern === 'string') {
pattern = new RegExp(`^${pattern}`);
}
this._userEvents.push({
pattern, listener
});
return this;
}
/**
* Listens on a command
* @param {string} command 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
*/
command(command, listener) {
const regex = /[^\s]+/;
const cmd = command.match(regex)[0].trim();
this._userEvents.push({
pattern: new RegExp(`^/${cmd}`),
parse: argumentParser.bind(null, command),
listener
});
return this;
}
/**
* 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
*/
send(message) {
return message.send(this).catch(console.error);
}
/**
* Stops the bot, deattaching all listeners and polling
*/
stop() {
this._stop = true;
if (this._webhookServer) {
this._webhookServer.close();
}
this.removeListener('update', this._update);
this._events = {};
}
/**
* The internal update event listener, used to parse messages and fire
* command/get events - YOU SHOULD NOT USE THIS
*
* @param {object} update
*/
_update(update) {
if (!this.update.offset) {
const updateId = update[update.length - 1].update_id;
this.update.offset = updateId;
}
if (this.update) {
this.update.offset += 1;
}
update.forEach(res => {
let text = res.message.text;
if (!text) {
return;
}
const selfUsername = `@${this.info.username}`;
if (text.startsWith('/') && text.indexOf(selfUsername) > -1) {
// Commands are sent in /command@thisusername format in groups
const regex = new RegExp(`(/.*)@${this.info.username}`);
text = text.replace(regex, '$1');
res.message.text = text;
}
let ev = this._userEvents.find(({pattern}) => pattern.test(text));
if (!ev) {
this.emit('command-notfound', res.message);
return;
}
if (!ev.parse) {
ev.listener(res.message);
return;
}
let {params, args} = ev.parse(res.message.text);
res.message.args = args;
const requiredParams = Object.keys(params).filter(param => {
return params[param] === REQUIRED && !args[param];
});
if (!requiredParams.length) {
ev.listener(res.message);
return;
}
const bot = this;
function* getAnswer() {
for (let param of requiredParams) {
const msg = new Message().to(res.message.chat.id)
.text(`Enter value for ${param}`);
yield bot.send(msg).then(answer => {
args[param] = answer.text;
});
}
}
const iterator = getAnswer();
(function loop() {
const next = iterator.next();
if (next.done) {
ev.listener(res.message);
return;
}
next.value.then(loop);
}());
});
}
}
export {
File,
Message,
BulkMessage,
Forward,
Question,
Keyboard
};

101
src/types/Base.js Normal file
View File

@ -0,0 +1,101 @@
import {EventEmitter} from 'events';
const ANSWER_THRESHOLD = 10;
/**
* Base class of all classes
*/
export default class Base extends EventEmitter {
constructor(method) {
super();
this.method = method;
this.properties = {};
}
/**
* 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
*/
send(bot) {
if (this._keyboard) {
const reply_markup = JSON.stringify(this._keyboard.getProperties());
this.properties.reply_markup = reply_markup;
}
let messageId;
return new Promise(resolve => {
bot.api[this.method](this.properties).then(response => {
messageId = response.result.message_id;
this.emit('message:sent', response);
});
if (this._keyboard.one_time_keyboard) {
this._keyboard.replyMarkup = '';
}
const chat = this.properties.chat_id;
let answers = 0;
bot.on('update', function listener(result) {
answers += result.length;
const update = result.find(({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.reply_to_message.message_id === messageId;
} else {
return message.chat.id === chat;
}
});
if (update) {
resolve(update.message);
this.emit('message:answer', update.message);
bot.removeListener('update', listener);
}
if (answers >= ANSWER_THRESHOLD) {
bot.removeListener('update', listener);
}
});
});
}
/**
* Returns properties of the object
* @return {object} properties of object
*/
getProperties() {
return this.properties;
}
/**
* 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)
*/
setProperties(object, extend = true) {
this.properties = extend ? Object.assign(this.properties, object)
: object;
return this.getProperties();
}
}

45
src/types/BulkMessage.js Normal file
View File

@ -0,0 +1,45 @@
import Message from './Message';
/**
* Message class, used to send a message to multiple chats
*/
export default class BulkMessage extends Message {
/**
* Create a new message
* @param {object} properties Message properties, as defined by Telegram API
*/
constructor(properties = {}) {
super(properties);
this.chats = [];
}
/**
* Set multiple chat_id's for the message
* @param {number} chat
* @return {object} returns the message object
*/
to(...args) {
const chats = args.reduce((a, b) => {
return a.concat(b);
}, []);
this.chats = chats;
return this;
}
/**
* Send the message to all chats
* @param {Bot} bot
* @return {Promise} Resolved when the message is sent to all chats
*/
send(bot) {
const promises = this.chats.map(chat => {
const clone = Object.assign({}, this.properties);
const message = new Message(clone).to(chat);
return message.send(bot);
});
return Promise.all(promises);
}
}

98
src/types/File.js Normal file
View File

@ -0,0 +1,98 @@
import Base from './Base';
import mime from 'mime';
const TYPES = ['photo', 'video', 'document', 'audio'];
/**
* File class, used to send pictures/movies/audios/documents to chat
*/
export default class File extends Base {
/**
* Create a new file instance
* @param {object} properties File properties, as defined by Telegram API
*/
constructor(properties = {}) {
super('sendDocument');
this.properties = properties;
this._keyboard = new Base();
}
/**
* Set chat_id of the message
* @param {number} chat
* @return {object} returns the message object
*/
to(chat) {
this.properties.chat_id = chat;
return this;
}
/**
* Set file of the message
* @param {string} file File path
* @param {string} fileType (optional) if the first argument is a
* file_id string, this option indicates file type
* @return {object} returns the message object
*/
file(file, fileType) {
if (fileType) {
this.properties[fileType] = {file: file};
return this;
}
let [type, extension] = mime.lookup(file).split('/');
if (type === 'image') {
type = 'photo';
}
if (extension === 'gif') {
type = 'document';
}
if (TYPES.indexOf(type) === -1) {
type = 'document';
}
this.properties[type] = {file: file};
this.method = `send${type[0].toUpperCase() + type.slice(1)}`;
return this;
}
/**
* Set caption for photos
* @param {string} text caption's text
* @return {object} returns the message object
*/
caption(text) {
this.properties.caption = text;
return this;
}
/**
* 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
*/
reply(id) {
this.properties.reply_to_message_id = id;
return this;
}
/**
* 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
*/
keyboard(kb) {
this._keyboard = kb;
return this;
}
// This class inherits Base's send method
}

50
src/types/Forward.js Normal file
View File

@ -0,0 +1,50 @@
import Base from './Base';
/**
* Forward class, used to forward messages from a chat to another
*/
export default class Forward extends Base {
/**
* Create a new forward message
* @param {object} properties Forward Message properties, as defined by
* Telegram API
*/
constructor(properties = {}) {
super('forwardMessage');
this.properties = properties;
this._keyboard = new Base();
}
/**
* Set chat_id of the message
* @param {number} chat
* @return {object} returns the message object
*/
to(chat) {
this.properties.chat_id = chat;
return this;
}
/**
* Set from_chat_id, source of message's chat's id
* @param {number} chat Source chat id
* @return {object} returns the message object
*/
from(chat) {
this.properties.from_chat_id = chat;
return this;
}
/**
* Sets message_id, the message to forward from source to target chat
* @param {number} message ID of the message to forward
* @return {object} returns the message object
*/
message(message) {
this.properties.message_id = message;
return this;
}
// This class inherits Base's send method
}

85
src/types/Keyboard.js Normal file
View File

@ -0,0 +1,85 @@
import Base from './Base';
/**
* Keyboard class, used to configure keyboards for messages.
* You should pass your instance of this class to message.keyboard() method
*/
export default class Keyboard extends Base {
/**
* Create a new keyboard
* @param {object} properties Keyboard properties, as defined by Telegram API
* See ReplyKeyboardMarkup, ReplyKeyboardHide,
* ForceReply
*/
constructor(properties = {}) {
super();
this.properties = properties;
}
/**
* 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
*/
keys(keys) {
this.properties.keyboard = keys;
this.properties.hide_keyboard = false;
return this;
}
/**
* Set force_keyboard property of reply_markup
* @param {boolean} enable value of force_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
force(enable = true) {
this.properties.force_keyboard = enable;
return this;
}
/**
* Set resize_keyboard property of reply_markup
* @param {boolean} enable value of resize_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
resize(enable = true) {
this.properties.resize_keyboard = enable;
return this;
}
/**
* Set force_keyboard property of reply_markup
* @param {boolean} enable value of force_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
oneTime(enable = true) {
this.properties.one_time_keyboard = enable;
return this;
}
/**
* Set selective property of reply_markup
* @param {boolean} enable value of force_keyboard, defaults to true
* @return {object} returns the keyboard object
*/
selective(enable = true) {
this.properties.selective = enable;
return this;
}
/**
* Set hide_keyboard property of reply_markup to true
* @return {object} returns the keyboard object
*/
hide() {
this.properties = {
hide_keyboard: true
};
return this;
}
}

97
src/types/Message.js Normal file
View File

@ -0,0 +1,97 @@
import Base from './Base';
/**
* Message class, used to send message to a chat
*/
export default class Message extends Base {
/**
* Create a new message
* @param {object} properties Message properties, as defined by Telegram API
*/
constructor(properties = {}) {
super('sendMessage');
this.properties = properties;
this._keyboard = new Base();
}
/**
* Set chat_id of the message
* @param {number} chat
* @return {object} returns the message object
*/
to(chat) {
this.properties.chat_id = chat;
return this;
}
/**
* Set text of the message
* @param {string} text Message's content
* @return {object} returns the message object
*/
text(text) {
this.properties.text = text;
return this;
}
/**
* Set text of the message in HTML format
* @param {string} text Message's content in HTML format
* @return {object} returns the message object
*/
html(text) {
this.properties.parse_mode = 'HTML';
if (text) {
this.properties.text = text;
}
return this;
}
/**
* Set text of the message in Markdown format
* @param {string} text Message's content in Markdown format
* @return {object} returns the message object
*/
markdown(text) {
this.properties.parse_mode = 'Markdown';
if (text) {
this.properties.text = text;
}
return this;
}
/**
* 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
*/
reply(id) {
this.properties.reply_to_message_id = id;
return this;
}
/**
* Set disable_web_page_preview of the message
* @param {boolean} enable
* @return {object} returns the message object
*/
preview(enable = true) {
this.properties.disable_web_page_preview = !enable;
return this;
}
/**
* 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
*/
keyboard(kb) {
this._keyboard = kb;
return this;
}
// This class inherits Base's send method
}

69
src/types/Question.js Normal file
View File

@ -0,0 +1,69 @@
import Message from './Message';
import Keyboard from './Keyboard';
/**
* Question class, extends Message
* Sends a message, shows a keyboard with the answers provided, and validates
* the answer
*/
export default class Question extends Message {
/**
* Create a new question
* @param {object} options Options, same as Message, plus `answers` which
* is a keyboard layout, see Keyboard#keys
*/
constructor(options = {}) {
super(options);
let kb = new Keyboard().force().oneTime().selective();
this.keyboard(kb);
this.answers(options.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
*/
answers(answers) {
this._answers = answers;
this._keyboard.keys(answers);
return this;
}
/**
* 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
*/
send(bot) {
const answers = this._answers;
return super.send(bot).then(message => {
let answer;
answers.forEach(function find(a) {
if (Array.isArray(a)) {
a.forEach(find);
}
if (a === message.text) {
answer = a;
}
});
if (answer) {
this.emit('question:answer', answer, message);
return message;
} else {
this.emit('question:invalid', message);
throw message;
}
});
}
}