Last active
July 6, 2016 17:08
-
-
Save daveroma/2004915f319dfae116ec0463790ddbda to your computer and use it in GitHub Desktop.
A node.js starter script that uses websockets to facilitate communication between a web client and a chat bot living at pandorabots.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const server = require('http').createServer(), | |
express = require('express'), | |
jade = require('jade'), | |
debug = require('debug')('loanbot:server'), | |
fs = require('fs'), | |
path = require('path') | |
WebSocketServer = require('ws').Server, | |
pandoraBot = require('pb-node'), | |
app = express(), | |
wss = new WebSocketServer({ server }), | |
port = normalizePort(process.env.PORT || '4090'), | |
options = { | |
url: 'https://aiaas.pandorabots.com', | |
app_id: 'pandorabots app id', | |
user_key: 'pandorabots user key', | |
botname: 'pandorabots bot name' | |
} | |
bot = new pandoraBot(options); | |
app.use(express.static(path.join(__dirname, '/public'))); | |
app.set('views', path.join(__dirname, 'views')); | |
app.set('view engine', 'jade'); | |
app.use( (req, res) => { res.render('home/index'); }); | |
wss.on('connection', (ws) => { | |
ws.on('message', (input) => { | |
bot.talk({ input }, (err, res) => { | |
if (err) | |
ws.send('Sorry I\'m having trouble collecting my thoughts'); | |
if (res.responses) | |
ws.send(res.responses[0]); | |
}); | |
fs.appendFile('input.txt', `${ input }\r\n`, (err) => { | |
if (err) | |
console.log(err); | |
}); | |
}); | |
}); | |
server.listen(port); | |
server.on('request', app); | |
server.on('error', onError); | |
server.on('listening', onListening); | |
function normalizePort(val) { | |
const port = parseInt(val, 10); | |
if (isNaN(port)) | |
return val; | |
if (port >= 0) | |
return port; | |
return false; | |
} | |
function onError(error) { | |
if (error.syscall !== 'listen') | |
throw error; | |
const bind = typeof port === 'string' | |
? `Pipe ${port}` | |
: `Port ${port}`; | |
// handle specific listen errors with friendly messages | |
switch (error.code) { | |
case 'EACCES': | |
console.error(`${bind} requires elevated privileges`); | |
process.exit(1); | |
break; | |
case 'EADDRINUSE': | |
console.error(`${bind} is already in use`); | |
process.exit(1); | |
break; | |
default: | |
throw error; | |
} | |
} | |
function onListening() { | |
const addr = server.address(); | |
const bind = typeof addr === 'string' | |
? `Pipe ${port}` | |
: `${port} addr.port`; | |
debug(`running on port: ${addr.port}`); | |
console.log(`running on port: ${addr.port}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment