Created
December 6, 2017 07:01
-
-
Save jazzyjackson/910d1b08e632f55e4ee16119082d50b0 to your computer and use it in GitHub Desktop.
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
#!/usr/local/bin/node | |
var net = require('net') | |
var util = require('util') | |
var os = require('os') | |
var port = process.env.CSPORT || 1024 | |
var host = process.env.CSHOST || 'localhost' | |
var identity = process.env.USER || 'unknown' /* not to be confused with 'nobody' */ | |
var botname = process.env.BOT || 'harry' | |
var chat = message => new Promise((resolve, reject)=> { | |
var client = net.createConnection({port: port, host: host}) | |
var buffers = [] | |
client.on('connect', () => client.write([identity,botname,message].join('\0') + '\0')) | |
client.on('data', data => buffers.push(data)) | |
client.on('error', error => reject(error)) | |
client.on('end', () => resolve(Buffer.concat(buffers).toString().trim())) | |
}) | |
function tryJSON(string){ | |
// if response from chatscript is valid json, I'll have an object ready to go, otherwise just a string is fine | |
try { | |
return JSON.parse(string) | |
} catch(e) { | |
return string | |
} | |
} | |
process.stdin.on('data', input => { | |
chat(input.toString()) | |
.then(response => { | |
var responseObj = tryJSON(response) | |
var string = typeof responseObj == 'object' ? JSON.stringify(responseObj) | |
: JSON.stringify({stdout: responseObj}) | |
process.stdout.write(string) | |
process.exit() | |
}) | |
.catch(error => { | |
process.stderr.write(util.inspect(error)) | |
process.exit() | |
}) | |
}) | |
module.exports = chat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment