-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebhooks.js
48 lines (40 loc) · 1.23 KB
/
webhooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// An example to show use of webhooks.
var contextMap = require('bot-context');
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express(); // Set up an express webservice. You can use restify, Koa etc.
app.use(bodyParser.json());
// Incoming webhook.
app.post('/recieve', (req, res) => {
let ctx = contextMap.getOrCreate(req.body.userId); // Assuming userId is in the json payload.
if (!ctx.isSet()) {
init(userId); // initialize the actions.
}
ctx.match(message, function (err, match, contextCb) {
if (!err) contextCb(userId, match);
});
});
function init(userId) {
let ctx = contextMap.getOrCreate(userId);
ctx.set(
/.*/, // The base matcher to match anything.
(match) => doSomethingAndRespond(userId));
}
function doSomethingAndRespond(userId) {
ctx.set(
// Set some more context here.
);
outgoingWebhook(userID, "bla bla");
}
function outgoingWebhook(userId, message) {
request.post({
url: 'https://<webhook-endpoint-here>',
form: {
userId: userId,
message: message
}
}, (err, resp, body) => {
// Handle webhook err/response.
});
}