How to start a conversation from nodejs client to microsoft bot - node.js

I'm trying to build an app that would send messages to a chat on Microsoft bot framework based on Directline lib, and reply with answer. The app is a web application where should send a POST request that should forward the message to the bot client, and reply with response of the bot from Microsoft bot framework.
An example of HTTP POST request:
http://host:port/api/message
BODY: {message:"Hi"}
It should send the "Hi" as a text to the relevant chat bot in the Microsoft Bot framework and reply with what ever the framework replys with.
I have put the secret and done all i think i should have done in order it to be working but, i'm having problem generating a conversation that should talk with the chat bot.
This is how i did it:
"use strict";
require('dotenv').config();
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require("body-parser");
var http = require('http');
var postLib = require("./lib");
var messageFilePath="message.out";
var cors = require('cors');
var uuid = require('uuid');
//new botclient
var client = require('directline-api');
// config items
var pollInterval = 1000;
var directLineSecret = 'secret';
var directLineClientName = 'DirectLineClient';
var directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';
///bot client end
var sendmail = require('sendmail')({silent: true})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.options('*', cors()); // include before other routes
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.post('/interact/message', cors(corsOptions), function(req, res) {
var uuid1 = uuid.v1();
var bodyMessage = JSON.stringify(req.body);
var log = uuid1 + ', ' + new Date().getTime() + ", " + bodyMessage;
if (req.query.botId == 1) {
emailMessage(log);
res.send(postLib.reply.reply);
}
if (req.query.botId == 2) {
botMessage(bodyMessage.message);
res.send(postLib.reply.reply);
}
});
function emailMessage(log){
sendmail({
from: postLib.mail.from,
to: postLib.mail.to,
subject: postLib.mail.subject,
html: 'this is the log: [' + log + ']',
}, function(err, reply) {
console.log(err && err.stack);
console.dir(reply);
});
fs.appendFile(messageFilePath, "\n" + log, function(error){
if (error) throw error;
});
}
function botMessage(message){
var token = client.getToken(directLineSecret);
// create a conversation
var conversationId = client.createConversation(token);
// post a message in a conversation
client.postMessage(token, conversationId, {
text: message
});
return client.getMessage(token, conversationId, 0);
}
var server = app.listen(8082, function () {
var host = server.address().address
var port = server.address().port
console.log("interact post server listening at http://%s:%s", host, port)
})

It's unclear the issue that you are having but I recommend you to check the Node.js Direct Line sample.

Related

twilio API keeps sending request until socket hangs up error occurs

I have been trying to solve this error from a long time. I could not find a similar problem online. I am sending a request through postman to twilio API for whatsapp. Everything seems ok. The promise should send a JSOM object in response but it keeps sending request until socket hangs up error occurs. Here is my code
const dotenv = require('dotenv').config();
const express = require('express');
const { response } = require('express');
const app = express();
app.use(express.json());
exports.sendMessages = function(sender, reciever, message) {
const accountSid = process.env.ACCOUNT_S_ID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
from: 'whatsapp:+'+sender,
body: message,
to: 'whatsapp:+'+reciever
})
.then(response => {
return {
data: JSON.stringify(response),
}})
.catch(e => { console.error('Got an error:', e.code, e.message); });
}
Calling the API
const express = require('express');
const app = express();
app.use(express.json());
// for parsing application/json
const send = require('./index');
let endPoint = process.env.ENDPOINT;
app.post(endPoint, function (req, res) {
send.sendMessages('14155238886', '393200149462','test message');
});
const port = process.env.PORT;
app.listen(port);
console.log('Successfully connected to ' +port);

Express + MQTT from POST request to publish in topic

I need a Node.js web service that accept a specific POST request that will trigger a publishing in a specific MQTT topic.
I use Express to listen for the request and this part of the script works fine.
The problem is when I it should trigger the publish in topic to perform a downlink.
The code without the Express part works fine. So It seems like Express interfere with MQTT. But the connection to the Broker works fine. Only the publish procedure doesn't work.
var express = require('express');
var bodyParser = require('body-parser');
var mqtt = require('mqtt')
var fs = require('fs')
var path = require('path')
const util = require('util')
var app = express();
var CERT = //certificate
var PORT = //port
var HOST = // host
var options = {
port: PORT,
host: HOST,
clientId: //client_id
username: //uname
password: //pswd
cert: CERT,
rejectUnauthorized: false,
protocol: 'mqtts'
}
var client;
var jsonParser = bodyParser.json();
var port = process.env.PORT || 8080;
app.use(express.static('public'));
app.get('/', function (req, res) {
res.render(__dirname + "/public/index.html");
})
client = mqtt.connect(options);
client.on("connect", () => {
console.log("MQTT connected");
})
client.on('message', function (topic, message) {
var msg = JSON.parse(message)
console.log("topic: " + topic + " msg:" + util.inspect(msg))
});
app.post('/', jsonParser, function (req, res) {
// Prepare output in JSON format
data = {
dev_id: req.body.dev_id,
pswd: req.body.password,
tx_cycle: req.body.tx_cycle
};
if (data.pswd != "password") {
console.log("Wrong password")
}
else {
console.log(data);
var topic = 'publish_topic';
var tx_cy = data.tx_cycle;
var msg = '{"port":"222","payload":"' + tx_cy + '","confirmed": false,"window":"BOTH","priority":0}';
console.log('Try to send downlink message, for ' + data.dev_id + ' set to ' + data.tx_cycle + ' min -> hex ' + tx_cy);
client.subscribe('reply/+/id/+');
client.publish(topic, msg);
res.status(200).send(msg + " sent to broker");
}
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
I solve the problem. The client id was refused by the broker because was not unique. Changing it solved the issue.

Make voice call using node js

I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue

node-rest-client: Can't set headers after they are sent.

I am trying to call a REST API from node using node-rest-client. In the event that my call returns an error, I want to catch the error and report it to the caller.
I am trying this with Postman, unfortunately this only works once. When I press send the second time, my node.js program crashes with the error "Can't set headers after they are sent."
I am new at node.js, so any help is highly appreciated!
//app stuff
const client_id = "x";
const client_secret = "y";
const callback = "https://myurl;
// Basic Setup
var http = require('http'),
express = require('express'),
mysql = require('mysql'),
parser = require('body-parser'),
Client = require('node-rest-client').Client;
var client = new Client();
// Setup express
var app = express();
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 5000);
// Set default route
app.get('/', function (req, res) {
res.send('<html><body><p>Welcome to Bank API Wrapper</p></body></html>');
});
app.post('/authorize', function (req,res) {
var response = [];
if (typeof req.body.code !== 'undefined' && typeof req.body.state !== 'undefined' ){
var code = req.body.code, state = req.body.state;
//conversion to base64 because citi api wants it this way
var authorization = "Basic " + Buffer.from(client_id + ":" + client_secret).toString('base64');
var args = {
data:{"grant_type":"authorization_code","code":code,"redirect_uri":callback},
headers:{"Authorization":authorization,"Content-Type":"application/x-www-form-urlencoded"}
};
//get access and refresh token
client.post("https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/sg/gcb", args, function (citidata, citiresponse) {
//console.log(citidata);
//console.log(citiresponse);
});
client.on('error', function (err) {
response.push({'result' : 'error', 'msg' : 'unauthorized access'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
});
}
else {
response.push({'result' : 'error', 'msg' : 'Please fill required details'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
// Create server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
You've got this:
client.on('error', function (err) {
This register an error handler on the client but it never gets removed. The client is shared between requests so any errors on subsequent requests will still fire the old error handlers.
Instead you can listen for an error on the request. Something like this:
var request = client.post("...
request.on('error', function(err) {
// handle error
});
See https://www.npmjs.com/package/node-rest-client#error-handling

Start a proxy server with nodejs so that it serves requests preprended with "/wps_proxy/wps_proxy?url="

I want to start a proxy server with node.js so that it serves requests preprended with "/wps_proxy/wps_proxy?url=". I want it so I can use the wps-js library of north52 (check the installation tips) . I have already a server where I run my application.
What I did try until now is :
the server.js file
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require("path");
var app = express();
app.use(express.static(__dirname + '/' + 'public'));
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//****** this is my try ******************************
app.get('/wps_proxy/wps_proxy',function (req,res){
res.sendfile(__dirname + '/' + 'public/wps_proxy/wps-js/target/wps-js-0.1.2-SNAPSHOT/example.html');
if(req.query !== undefined){//because it enters sometimes without url
var http = require('http');
//Options to be used by request
var options = {
host:"geostatistics.demo.52north.org",//fixed given data
port:"80",
path:"/wps/WebProcessingService"
};
var callback = function(response){
var dat = "";
response.on("data",function(data){
dat+=data;
});
response.on("end", function(){
res.end(dat)
})
};
//Make the request
var req = http.request(options,callback);
req.end()
}
})
var ipaddress = process.env.OPENSHIFT_NODEJS_IP||'127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.set('port', port);
app.listen(app.get('port'),ipaddress, function() {
console.log( 'Server started on port ' + app.get('port'))
})
//***************************************
but its not working.. I think that the data are not sent back correctly..
This is a live example of what I want to do.. http://geoprocessing.demo.52north.org/wps-js-0.1.1/
and this is a live example of my application (check the console for errors) http://gws-hydris.rhcloud.com/wps_proxy/wps_proxy
I did find my answer from this post How to create a simple http proxy in node.js? so the way i solve it was:
app.get('/wps_proxy/wps_proxy',function (req,res){
var queryData = url.parse(req.url, true).query;
if (queryData.url) {
request({
url: queryData.url
}).on('error', function(e) {
res.end(e);
}).pipe(res);
}
else {
res.end("no url found");
}
})

Resources