2015-06-26 17:20:54 +00:00
|
|
|
import API from './api';
|
|
|
|
import {EventEmitter} from 'events';
|
|
|
|
|
|
|
|
const DEFAULTS = {
|
|
|
|
update: {
|
|
|
|
offset: 0,
|
|
|
|
timeout: 0.5,
|
|
|
|
limit: 100
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export default class Bot {
|
|
|
|
constructor(options = {update: {}}) {
|
|
|
|
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);
|
|
|
|
|
2015-06-26 22:33:30 +00:00
|
|
|
this.msg = {};
|
|
|
|
|
2015-06-26 17:20:54 +00:00
|
|
|
// EventEmitter
|
|
|
|
this._events = {};
|
2015-06-26 22:33:30 +00:00
|
|
|
this._userEvents = [];
|
2015-06-26 17:20:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
2015-06-26 22:33:30 +00:00
|
|
|
let poll = function() {
|
2015-06-26 17:20:54 +00:00
|
|
|
this.api.getUpdates(this.update).then(response => {
|
2015-06-26 22:33:30 +00:00
|
|
|
setTimeout(poll, this.update.timeout * 1000);
|
2015-06-26 17:20:54 +00:00
|
|
|
|
|
|
|
const result = response.result;
|
|
|
|
if (!result.length) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.update.offset) {
|
|
|
|
const 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(res => {
|
2015-06-26 22:33:30 +00:00
|
|
|
let text = res.message.text;
|
2015-06-26 17:20:54 +00:00
|
|
|
if (text.indexOf('/') === 0) {
|
2015-06-26 22:33:30 +00:00
|
|
|
// Commands are sent in format /command@botusername format
|
|
|
|
const regex = new RegExp(`@${this.info.username}$`);
|
|
|
|
text = text.replace(regex, '');
|
2015-06-26 17:20:54 +00:00
|
|
|
}
|
2015-06-26 22:33:30 +00:00
|
|
|
|
|
|
|
let ev = this._userEvents.find(({message}) => message.test(text));
|
|
|
|
ev.listener(res);
|
2015-06-26 17:20:54 +00:00
|
|
|
});
|
|
|
|
});
|
2015-06-26 22:33:30 +00:00
|
|
|
}.bind(this);
|
|
|
|
|
2015-06-26 23:56:28 +00:00
|
|
|
return this.api.getMe().then(response => {
|
2015-06-26 22:33:30 +00:00
|
|
|
this.info = response.result;
|
|
|
|
poll();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
get(message, listener) {
|
|
|
|
if (typeof message === 'string') {
|
|
|
|
message = new RegExp(`^${message}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
this._userEvents.push({
|
|
|
|
message, listener
|
|
|
|
});
|
2015-06-26 17:20:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
command(cmd, listener) {
|
2015-06-26 22:33:30 +00:00
|
|
|
this._userEvents.push({
|
|
|
|
message: new RegExp(`/${cmd}`),
|
|
|
|
listener
|
|
|
|
});
|
2015-06-26 17:20:54 +00:00
|
|
|
}
|
|
|
|
|
2015-06-28 01:04:18 +00:00
|
|
|
send(message) {
|
|
|
|
return message.send(this);
|
2015-06-26 17:20:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Bot.prototype = Object.assign(Bot.prototype, EventEmitter.prototype);
|