Node JS

Sample Code in Node JS with Express Server

Here it goes the example of how to implement a very simple β€œparrot” bot (that replies exactly what has been said to it) using Node.js with an Express server:
The below sample code is shared by one of the picky assist customer based in Chile.
1
const bodyParser = require('body-parser');
2
const express = require('express');
3
const app = express();
4
​
5
// enable extended to let nested POST
6
app.use(bodyParser.urlencoded({extended: true}));
7
​
8
// webhook set up
9
// on production authenticate each POST - you could add a token to the URL
10
app.post('/webhook/', (req, res) => {
11
// for development only - console log the post content
12
console.log(req.body);
13
​
14
// builds the answer replicating the message sent
15
let reply = {
16
'message-out': req.body['message-in'],
17
'delay': 0,
18
};
19
​
20
// Sends the reply - ENSURE a JSON response add JSON.stringfy just to be safe
21
res.status(200).send(JSON.stringify(reply));
22
});
23
​
24
// Sets server port and logs message on success
25
app.listen(process.env.PORT || 6000, () => console.log('server is listening'));
Copied!

Node Js - Push API -Http method

1
var http = require("https");
2
​
3
var options = {
4
"method": "POST",
5
"hostname": "pickyassist.com",
6
"port": null,
7
"path": "/app/api/v2/push",
8
"headers": {
9
"content-type": "application/json",
10
}
11
};
12
​
13
var req = http.request(options, function (res) {
14
var chunks = [];
15
​
16
res.on("data", function (chunk) {
17
chunks.push(chunk);
18
});
19
​
20
res.on("end", function () {
21
var body = Buffer.concat(chunks);
22
console.log(body.toString());
23
});
24
});
25
​
26
req.write(JSON.stringify({
27
token: 'c2a0b6221c5dd55ceb09ae1f74e46521756d',
28
'priority ': 0,
29
application: '2',
30
sleep: 0,
31
globalmessage: '',
32
globalmedia: '',
33
data: [{number: '1212', message: 'Test'}]
34
}));
35
req.end();
Copied!

Node Js - Unirest

1
var unirest = require("unirest");
2
​
3
var req = unirest("POST", "https://pickyassist.com/app/api/v2/push");
4
​
5
​
6
req.headers({
7
"content-type": "application/json"
8
});
9
​
10
req.type("json");
11
req.send({
12
"token": "c2a0b6221c5dd55ceb09ae1f74e46521756d",
13
"priority ": 0,
14
"application": "2",
15
"sleep": 0,
16
"globalmessage": "",
17
"globalmedia": "",
18
"data": [
19
{
20
"number": "1212",
21
"message": "Test"
22
}
23
]
24
});
25
​
26
req.end(function (res) {
27
if (res.error) throw new Error(res.error);
28
​
29
console.log(res.body);
30
});
31
​
Copied!
Last modified 2yr ago