Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to regex postbacks #119

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion lib/BootBot.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
}

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down