-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
65 lines (54 loc) · 1.82 KB
/
server.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'use strict'
const express = require('express')
const http = require('http')
const WebSocket = require('ws')
const app = express() // Get an application instance of 'express'
const port = process.env.PORT || 5000
const api = require('./api/answers.json')
let questions = api.map((item) => {
return item.question
})
app.use(express.static('public'))
app.locals.appTitle = 'TinkerBot ChatBot'
// Setup PUG as templating language
app.set('view engine', 'pug')
app.get('/', (req, res) => {
res.render('index')
})
// Invoke express get method...
app.get('/api', (request, response) => {
// Output the bot answers,
response.json(api)
})
// Connect express app and the websocket server
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })
// When new socket connected, this will fire up
// First argument is an 'individual' socket ('ws')
// Think of a websocket as a connected endpoint
// Every client that connects will call this on function to fire
wss.on('connection', (ws, req) => {
// Add listeners to the WebSocket
ws.on('message', (message) => {
if (message === 'exit') {
ws.send(`You have disconnected`)
ws.close()
} else {
// All socket clients are placed in an array
wss.clients.forEach((client) => {
// Send message to each client in the loop
client.send(message)
// Loop through Q/A API
questions.forEach((question, index) => {
if (message.toLowerCase() === question) {
client.send(`TinkerBot: ${api[index].answer}`)
}
})
})
}
})
// Static welcome message sent from server
ws.send(`TinkerBot: Hi friend! I answer questions! Type '-help' for tips`)
})
// The express app should listen to this port
server.listen(port, () => console.log(`Listening on port: ${server.address().port}`))