diff --git a/lib/BootBot.js b/lib/BootBot.js index 5df40f8..9b2296c 100644 --- a/lib/BootBot.js +++ b/lib/BootBot.js @@ -35,6 +35,7 @@ class BootBot extends EventEmitter { this.webhook = this.webhook.charAt(0) !== '/' ? `/${this.webhook}` : this.webhook; this.app.use(this.webhook, bodyParser.json({ verify: this._verifyRequestSignature.bind(this) })); this._hearMap = []; + this._postbackMap = []; this._conversations = []; } @@ -457,6 +458,12 @@ class BootBot extends EventEmitter { return this; } + postback(keywords, callback) { + keywords = Array.isArray(keywords) ? keywords : [keywords]; + keywords.forEach(keyword => this._postbackMap.push({ keyword, callback })); + return this; + } + /** * Modules are simple functions that you can use to organize your code in different files and folders. * @param {Function} factory Called immediatly and receives the bot instance as its only parameter. @@ -573,7 +580,30 @@ class BootBot extends EventEmitter { _handlePostbackEvent(event) { if (this._handleConversationResponse('postback', event)) { return; } const payload = event.postback.payload; - if (payload) { + const senderId = event.sender.id; + if (payload) { + let captured = false; + + this._postbackMap.forEach(postback => { + if (typeof postback.keyword === 'string' && postback.keyword.toLowerCase() === payload.toLowerCase()) { + const res = postback.callback.apply(this, [event, new Chat(this, senderId), { + keyword: postback.keyword, + captured + }]); + captured = true; + return res; + } else if (postback.keyword instanceof RegExp && postback.keyword.test(payload)) { + const res = postback.callback.apply(this, [event, new Chat(this, senderId), { + keyword: postback.keyword, + match: payload.match(postback.keyword), + captured + }]); + captured = true; + return res; + } + }); + if (captured) return; + this._handleEvent(`postback:${payload}`, event); } this._handleEvent('postback', event);