// dialogflow const dialogflow = require('dialogflow'); // server and websocket const WebSocket = require('ws'); const http = require('http'); const path = require('path'); const express = require('express'); const webSocketsServerPort = 8000; const serverpath = '/ws'; const app = express(); const router = express.Router(); router.get('/', function (req, res) { res.sendFile(path.join(__dirname + '/index.html')); }); app.use(express.static(__dirname + '/../client')); app.use('/', router); var server = http.createServer(app); server.listen(process.env.port || webSocketsServerPort, function () { console.log((new Date()) + ' Server is listening on port ' + webSocketsServerPort); }); const wss = new WebSocket.Server({ server: server, path: serverpath }); wss.on('connection', function connection (ws) { ws.id = wss.getUniqueID(); console.log(ws.id + ' connected'); ws.on('message', function incoming (message) { promptQuery(message, ws); }); ws.on('close', function (connection) { // close user connection }); }); const projectId = 'digitalerdemenztest'; const sessionClient = new dialogflow.SessionsClient({ keyFilename: 'dialogflow_cred_dem.json' }); // Send request and log result function promptQuery (prompt, wsock) { let sessionId = wsock.id; let sessionPath = sessionClient.sessionPath(projectId, sessionId); const request = { session: sessionPath, queryInput: { text: { text: prompt, languageCode: 'de-DE' } } }; sessionClient .detectIntent(request) .then(responses => { const result = responses[0].queryResult; console.log(` Query: ${result.queryText}`); console.log(` Response: ${result.fulfillmentText}`); if (result.intent) { console.log(` Intent: ${result.intent.displayName}`); } else { console.log(` No intent matched.`); } wsock.send(JSON.stringify(result)); // checkIntent(result) }) .catch(err => { console.error('ERROR:', err); }); } // create unique id wss.getUniqueID = function () { function s4 () { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + '-' + s4(); };