From 72081e30ab344abb91e3c88a5dd28d01c2257ccc Mon Sep 17 00:00:00 2001 From: Janis Peisenieks Date: Sat, 10 Mar 2018 22:44:53 +0200 Subject: [PATCH] Add ability to regex postbacks --- lib/BootBot.js | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/BootBot.js b/lib/BootBot.js index 9808bb8..8c522ad 100644 --- a/lib/BootBot.js +++ b/lib/BootBot.js @@ -23,6 +23,7 @@ class BootBot extends EventEmitter { this.webhook = this.webhook.charAt(0) !== '/' ? `/${this.webhook}` : this.webhook; this.app.use(bodyParser.json({ verify: this._verifyRequestSignature.bind(this) })); this._hearMap = []; + this._postbackMap = []; this._conversations = []; } @@ -270,6 +271,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; + } + module(factory) { return factory.apply(this, [this]); } @@ -364,7 +371,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);