mirror of
https://github.com/yagop/node-telegram-bot-api
synced 2025-08-29 13:27:44 +00:00
Method bot.onText
This commit is contained in:
parent
9863172779
commit
cfd32f47bf
@ -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;
|
||||
|
@ -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
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user