diff --git a/src/telegram.js b/src/telegram.js index 63b6711..e5fe1c6 100644 --- a/src/telegram.js +++ b/src/telegram.js @@ -41,6 +41,7 @@ var TelegramBot = function (token, options) { 'location', 'new_chat_participant', 'left_chat_participant', 'new_chat_title', 'new_chat_photo', 'delete_chat_photo', 'group_chat_created' ]; // Telegram message events + this.textRegexpCallbacks = []; this.processUpdate = this._processUpdate.bind(this); @@ -76,6 +77,17 @@ TelegramBot.prototype._processUpdate = function (update) { } }; this.messageTypes.forEach(processMessageType.bind(this)); + if (message.text) { + debug('Text message'); + this.textRegexpCallbacks.forEach(function (reg) { + debug('Matching %s whith', message.text, reg.regexp); + var result = reg.regexp.exec(message.text); + if (result) { + debug('Matches', reg.regexp); + reg.callback(message, result); + } + }); + } } }; @@ -476,4 +488,14 @@ TelegramBot.prototype.downloadFile = function(fileId, downloadDir) { }; +/** + * Register a RegExp to test against an incomming text message + * @param {RegExp} regexp [RegExp to be executed with `exec`] + * @param {Function} fn [Callback receives 2 parameters, the msg and the + * result of executing `regexp.exec` on message text] + */ +TelegramBot.prototype.onText = function (regexp, fn) { + this.textRegexpCallbacks.push({regexp: regexp, callback: fn}); +}; + module.exports = TelegramBot; diff --git a/test/index.js b/test/index.js index e10628b..6d1e6e6 100644 --- a/test/index.js +++ b/test/index.js @@ -463,7 +463,24 @@ describe('Telegram', function () { }); }); - + it('should call `onText` callback on match', function (done) { + var bot = new Telegram(TOKEN, {webHook: true}); + bot.onText(/\/echo (.+)/, function (msg, match) { + bot._WebHook._webServer.close(); + match[1].should.be.exactly('ECHO ALOHA'); + done(); + }); + var url = 'http://localhost:8443/bot'+TOKEN; + request({ + url: url, + method: 'POST', + json: true, + headers: { + 'content-type': 'application/json', + }, + body: {update_id: 0, message: {text: '/echo ECHO ALOHA'}} + }); + }); }); // End Telegram