You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ws-server.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // dialogflow
  2. const dialogflow = require('dialogflow');
  3. // server and websocket
  4. const WebSocket = require('ws');
  5. const http = require('http');
  6. const path = require('path');
  7. const express = require('express');
  8. const webSocketsServerPort = 8000;
  9. const serverpath = '/ws';
  10. const app = express();
  11. const router = express.Router();
  12. router.get('/', function (req, res) {
  13. res.sendFile(path.join(__dirname + '/index.html'));
  14. });
  15. app.use(express.static(__dirname + '/../client'));
  16. app.use('/', router);
  17. var server = http.createServer(app);
  18. server.listen(process.env.port || webSocketsServerPort, function () {
  19. console.log((new Date()) + ' Server is listening on port ' +
  20. webSocketsServerPort);
  21. });
  22. const wss = new WebSocket.Server({ server: server, path: serverpath });
  23. wss.on('connection', function connection (ws) {
  24. ws.id = wss.getUniqueID();
  25. console.log(ws.id + ' connected');
  26. ws.on('message', function incoming (message) {
  27. promptQuery(message, ws);
  28. });
  29. ws.on('close', function (connection) {
  30. // close user connection
  31. });
  32. });
  33. const projectId = 'digitalerdemenztest';
  34. const sessionClient = new dialogflow.SessionsClient({
  35. keyFilename: 'dialogflow_cred_dem.json'
  36. });
  37. // Send request and log result
  38. function promptQuery (prompt, wsock) {
  39. let sessionId = wsock.id;
  40. let sessionPath = sessionClient.sessionPath(projectId, sessionId);
  41. const request = {
  42. session: sessionPath,
  43. queryInput: {
  44. text: {
  45. text: prompt,
  46. languageCode: 'de-DE'
  47. }
  48. }
  49. };
  50. sessionClient
  51. .detectIntent(request)
  52. .then(responses => {
  53. const result = responses[0].queryResult;
  54. console.log(` Query: ${result.queryText}`);
  55. console.log(` Response: ${result.fulfillmentText}`);
  56. if (result.intent) {
  57. console.log(` Intent: ${result.intent.displayName}`);
  58. } else {
  59. console.log(` No intent matched.`);
  60. }
  61. wsock.send(JSON.stringify(result));
  62. // checkIntent(result)
  63. })
  64. .catch(err => {
  65. console.error('ERROR:', err);
  66. });
  67. }
  68. // create unique id
  69. wss.getUniqueID = function () {
  70. function s4 () {
  71. return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  72. }
  73. return s4() + s4() + '-' + s4();
  74. };