diff --git a/.gitignore b/.gitignore index c2658d7..63746a6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ node_modules/ +.python-version +/log/log.json +/config/index.js diff --git a/src/js/ip.js b/src/js/ip.js index 0c2749c..bf30135 100644 --- a/src/js/ip.js +++ b/src/js/ip.js @@ -1 +1 @@ -var ip_addr ="192.168.0.38"; \ No newline at end of file +var ip_addr ="192.168.0.169"; \ No newline at end of file -- knotmirror 0.0.1 From a326f04f6ee9c1fad3614104b8487d2204a7c7e0 Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 21:12:13 +0100 Subject: [PATCH 2/8] style --- log/index.js | 74 +++++++------- log/log.json | 4 + log/responses.json | 6 ++ response/index.js | 15 ++- server.js | 60 ++++++------ skills/coin/index.js | 14 +-- skills/fact/duckduckgo/index.js | 26 +++-- skills/fact/google/index.js | 156 +++++++++++++----------------- skills/fact/index.js | 41 ++++---- skills/fact/wolframalpha/index.js | 60 ++++++------ skills/joke/index.js | 22 ++--- skills/movie/index.js | 26 ++--- skills/news/index.js | 41 ++++---- skills/shuttlelaunch/index.js | 26 ++--- skills/song/index.js | 25 +++-- skills/time/index.js | 18 ++-- skills/timer/index.js | 38 ++++---- skills/weather/index.js | 153 ++++++++++++++--------------- 18 files changed, 392 insertions(+), 413 deletions(-) diff --git a/log/index.js b/log/index.js index 01c6e76..abede10 100644 --- a/log/index.js +++ b/log/index.js @@ -1,58 +1,58 @@ -'use strict'; +'use strict' -var fs = require('co-fs'); +const fs = require('co-fs') -function* log_query(query){ - var queries_obj = require('./log.json'), - entry = {"query":query, "timestamp":Math.round(+new Date()/1000)}; +function * log_query(query) { + let queries_obj = require('./log.json'), + entry = {query, timestamp: Math.round(Number(new Date()) / 1000)} - var queries = queries_obj.queries; + const queries = queries_obj.queries - queries.push(entry); + queries.push(entry) - queries_obj.queries = queries; + queries_obj.queries = queries - yield fs.writeFile('./log/log.json', JSON.stringify(queries_obj,null,4)); + yield fs.writeFile('./log/log.json', JSON.stringify(queries_obj, null, 4)) - return; + return } -function* log_response(query,response,skill){ - var responses_obj = require('./responses.json'), - entry = {"query":query, "response":response,"skill":skill,"timestamp":Math.round(+new Date()/1000)}; +function * log_response(query, response, skill) { + let responses_obj = require('./responses.json'), + entry = {query, response, skill, timestamp: Math.round(Number(new Date()) / 1000)} - var responses = responses_obj.responses; + const responses = responses_obj.responses - responses.push(entry); + responses.push(entry) - responses_obj.responses = responses; + responses_obj.responses = responses - yield fs.writeFile('./log/responses.json', JSON.stringify(responses_obj,null,4)); + yield fs.writeFile('./log/responses.json', JSON.stringify(responses_obj, null, 4)) - return; + return } -function* get_last_query(){ - var queries = require('./log.json').queries; - if (queries && queries.length){ - return queries[0]; - } else { - return null; - } +function * get_last_query() { + const queries = require('./log.json').queries + if (queries && queries.length) { + return queries[0] + } else { + return null + } } -function* get_last_response(){ - var responses = require('./responses.json').responses; - if (responses && responses.length){ - return responses[0]; - } else { - return null; - } +function * get_last_response() { + const responses = require('./responses.json').responses + if (responses && responses.length) { + return responses[0] + } else { + return null + } } module.exports = { - add: log_query, - get_last: get_last_query, - response: log_response, - get_last_response: get_last_response -}; \ No newline at end of file + add: log_query, + get_last: get_last_query, + response: log_response, + get_last_response +} diff --git a/log/log.json b/log/log.json index 939da23..9bf90fb 100644 --- a/log/log.json +++ b/log/log.json @@ -51,6 +51,10 @@ { "query": "set a timer for 3 minutes", "timestamp": 1485531393 + }, + { + "query": "whats the wather?", + "timestamp": 1485547698 } ] } \ No newline at end of file diff --git a/log/responses.json b/log/responses.json index ce01e73..ddadb1d 100644 --- a/log/responses.json +++ b/log/responses.json @@ -71,6 +71,12 @@ "response": ":timer: 3 minutes", "skill": "timer", "timestamp": 1485531393 + }, + { + "query": "whats the wather?", + "response": "It is currently -6° with Mist", + "skill": "weather", + "timestamp": 1485547698 } ] } \ No newline at end of file diff --git a/response/index.js b/response/index.js index dffb078..739dc7b 100644 --- a/response/index.js +++ b/response/index.js @@ -1,14 +1,11 @@ -'use strict'; +function * handle_response(request) { + console.log(request) -function *handle_response(request) { - console.log(request); + const funct = require('../skills/' + request.responseType) - var funct = require('../skills/'+request.responseType); - var response = yield funct.get(request.originalQuery); - - return response; + return yield funct.get(request.originalQuery) } module.exports = { - get : handle_response -}; \ No newline at end of file + get: handle_response +} diff --git a/server.js b/server.js index e8e9cf6..7414433 100644 --- a/server.js +++ b/server.js @@ -1,49 +1,49 @@ -var express = require('express'); -var app = express(); -var wrap = require('co-express'); -var compression = require('compression'); -var fs = require('fs'); -var ip = require("ip"); +const express = require('express') +const app = express() +const wrap = require('co-express') +const compression = require('compression') +const fs = require('fs') +const ip = require('ip') -var search = require('./api/core-ask.js'); +const search = require('./api/core-ask.js') -var address = 'var ip_addr ="' + ip.address() + '";'; +const address = 'var ip_addr ="' + ip.address() + '";' -fs.writeFile("./src/js/ip.js", address, function(err) { +fs.writeFile('./src/js/ip.js', address, err => { if (err) { - return console.log(err); + return console.log(err) } - console.log(ip.address()); -}); + console.log(ip.address()) +}) app.use(compression({ threshold: 0, level: 9, memLevel: 9 -})); +})) -app.use(function(req, res, next) { - req.connection.setNoDelay(true); - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); - next(); -}); +app.use((req, res, next) => { + req.connection.setNoDelay(true) + res.header('Access-Control-Allow-Origin', '*') + res.header('Access-Control-Allow-Headers', 'X-Requested-With') + next() +}) -app.use(express.static('./src')); +app.use(express.static('./src')) -app.get('/api/ask', wrap(function*(req, res) { - var input = req.query['q'].toLowerCase(); +app.get('/api/ask', wrap(function *(req, res) { + const input = req.query.q.toLowerCase() - res.header("Content-Type", "application/json"); + res.header('Content-Type', 'application/json') try { - var result = yield search.query(input); - res.send(result); + const result = yield search.query(input) + res.send(result) } catch (e) { - console.log(e); - res.send({msg:"Sorry, I didnt understand "+input, type:"error",msg:input}); + console.log(e) + res.send({ msg: 'Sorry, I didnt understand ' + input, type: 'error' }) } -})); +})) -app.listen(4567); -console.log('P-Brain is listening on port 4567'); \ No newline at end of file +app.listen(4567) +console.log('http://localhost:4567') diff --git a/skills/coin/index.js b/skills/coin/index.js index e6b3605..9bce631 100644 --- a/skills/coin/index.js +++ b/skills/coin/index.js @@ -1,14 +1,14 @@ -function * coin_resp(){ - var state = (Math.floor(Math.random() * 2) == 0) ? 'heads' : 'tails'; +function * coin_resp() { + const state = (Math.floor(Math.random() * 2) == 0) ? 'heads' : 'tails' - return "It's " + state; + return 'It\'s ' + state } -function * _intent(){ - return {keywords:['heads or tails','flip a coin','toss a coin'], module:'coin'}; +function * _intent() { + return {keywords: ['heads or tails', 'flip a coin', 'toss a coin'], module: 'coin'} } module.exports = { - get: coin_resp, - intent: _intent + get: coin_resp, + intent: _intent } diff --git a/skills/fact/duckduckgo/index.js b/skills/fact/duckduckgo/index.js index a2a1cc8..007a9da 100644 --- a/skills/fact/duckduckgo/index.js +++ b/skills/fact/duckduckgo/index.js @@ -1,30 +1,28 @@ -'use strict'; +const request = require('co-request') -var request = require('co-request'); +function * ddg_resp(query) { + const ddg_url = 'http://api.duckduckgo.com/?q=&format=json&pretty=1' -function* ddg_resp(query) { - var ddg_url = 'http://api.duckduckgo.com/?q=&format=json&pretty=1'; - - var data = yield request(ddg_url.replace('', query)); + let data = yield request(ddg_url.replace('', query)) try { - data = JSON.parse(data.body); + data = JSON.parse(data.body) } catch (e) { if (e) { - console.log('error parsing duckduckgo body ' + e); + console.log('error parsing duckduckgo body ' + e) } - return null; + return null } - var resp = data.AbstractText; + const resp = data.AbstractText - if (resp.split('.')[1] && resp.split('.')[1] !== "") { - return resp.split('.')[0]; + if (resp.split('.')[1] && resp.split('.')[1] !== '') { + return resp.split('.')[0] } else { - return resp; + return resp } } module.exports = { get: ddg_resp -} \ No newline at end of file +} diff --git a/skills/fact/google/index.js b/skills/fact/google/index.js index db75988..b669736 100644 --- a/skills/fact/google/index.js +++ b/skills/fact/google/index.js @@ -1,190 +1,170 @@ -'use strict'; - -var request = require('co-request'), +let request = require('co-request'), $ = require('cheerio'), Entities = require('html-entities').XmlEntities, entities = new Entities(), striptags = require('striptags'), tabletojson = require('tabletojson'), xray = require('x-ray')(), - json2csv = require('json2csv'); + json2csv = require('json2csv') -function* google_resp(query) { +function * google_resp(query) { // Remove spaces and replace with + - query = query.toLowerCase(); - query = query.replace('ask google', ''); - query = query.replace(" ", "+"); + query = query.toLowerCase() + query = query.replace('ask google', '') + query = query.replace(' ', '+') // Remove _ and replace with + - query = query.replace(/ /g, "+"); - + query = query.replace(/ /g, '+') - var userAgent = [ + const userAgent = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' - ]; + ] - var sel = Math.floor((Math.random() * 5)); - var userAgentRandom = userAgent[sel]; - var items; + const sel = Math.floor((Math.random() * 5)) + const userAgentRandom = userAgent[sel] + let items // Create search sring - var queryString = "http://www.google.com/search?q=" + query + '&oe=utf8'; + const queryString = 'http://www.google.com/search?q=' + query + '&oe=utf8' - var options = { + const options = { uri: queryString, 'User-Agent': userAgentRandom - }; + } - var body = yield request(options); + let body = yield request(options) - body = body.body; + body = body.body // result variable init - var found = 0; + let found = 0 - //how many 2 + // how many 2 if (!found) { - //how many - items = $('._m3b', body).get().length; // find how many lines there are in answer table + // how many + items = $('._m3b', body).get().length // find how many lines there are in answer table if (items) { - found = $('._eGc', body).html() + ", "; - + found = $('._eGc', body).html() + ', ' for (var count = 0; count < items; count++) { - found = found + $('._m3b', body).eq(count).html() + ", "; + found = found + $('._m3b', body).eq(count).html() + ', ' } } } - //name list + // name list if (!found && $('#_vBb', body).length > 0) { - - found = $('#_vBb', body).html(); + found = $('#_vBb', body).html() } - //facts 1 + // facts 1 if (!found && $('._tXc>span', body).length > 0) { - - found = $('._tXc>span', body).html(); + found = $('._tXc>span', body).html() } - //facts 2 + // facts 2 if (!found && $('._sPg', body).length > 0) { - - found = " " + $('._sPg', body).html(); + found = ' ' + $('._sPg', body).html() } - //instant + description 1 + // instant + description 1 if (!found && $('._Oqb', body).length > 0) { + found = $('._Oqb', body).html() - found = $('._Oqb', body).html(); - - //how many 1 + // how many 1 if ($('._Mqb', body).length > 0) { - - found += " " + $('._Mqb', body).html(); + found += ' ' + $('._Mqb', body).html() } } - //instant + description 2 + // instant + description 2 if (!found && $('._o0d', body).length > 0) { + const tablehtml = $('._o0d', body).html() - var tablehtml = $('._o0d', body).html(); - - found = tablehtml; - - xray(tablehtml, ['table@html'])(function(conversionError, tableHtmlList) { + found = tablehtml + xray(tablehtml, ['table@html'])((conversionError, tableHtmlList) => { if (tableHtmlList) { // xray returns the html inside each table tag, and tabletojson // expects a valid html table, so we need to re-wrap the table. - var table1 = tabletojson.convert('' + tableHtmlList[0] + '
'); + const table1 = tabletojson.convert('' + tableHtmlList[0] + '
') - var csv = json2csv({ + let csv = json2csv({ data: table1, hasCSVColumnTitle: false - }); + }) - csv = csv.replace(/(['"])/g, ""); - csv = csv.replace(/\,(.*?)\:/g, ", "); - csv = csv.replace(/\{(.*?)\:/g, ", "); + csv = csv.replace(/(['"])/g, '') + csv = csv.replace(/\,(.*?)\:/g, ', ') + csv = csv.replace(/\{(.*?)\:/g, ', ') - found = csv.toString(); + found = csv.toString() } - }); + }) } - //Time, Date + // Time, Date if (!found && $('._rkc._Peb', body).length > 0) { - - found = $('._rkc._Peb', body).html(); - + found = $('._rkc._Peb', body).html() } - //Maths + // Maths if (!found && $('.nobr>.r', body).length > 0) { - found = $('.nobr>.r', body).html(); + found = $('.nobr>.r', body).html() } - //simple answer + // simple answer if (!found && $('.obcontainer', body).length > 0) { - found = $('.obcontainer', body).html(); - + found = $('.obcontainer', body).html() } - //Definition + // Definition if (!found && $('.r>div>span', body).first().length > 0) { - found = $('.r>div>span', body).first().html() + " definition. "; - items = $('.g>div>table>tr>td>ol>li', body).get().length; // find how many lines there are in answer table + found = $('.r>div>span', body).first().html() + ' definition. ' + items = $('.g>div>table>tr>td>ol>li', body).get().length // find how many lines there are in answer table if (items) { - for (var count = 0; count < items; count++) { - - found = found + $('.g>div>table>tr>td>ol>li', body).eq(count).html() + ", "; + found = found + $('.g>div>table>tr>td>ol>li', body).eq(count).html() + ', ' } } } - //TV show + // TV show if (!found && $('._B5d', body).length > 0) { - found = $('._B5d', body).html(); + found = $('._B5d', body).html() if ($('._Pxg', body).length > 0) { - found += ". " + $('._Pxg', body).html(); + found += '. ' + $('._Pxg', body).html() } if ($('._tXc', body).length > 0) { - - found += ". " + $('._tXc', body).html(); + found += '. ' + $('._tXc', body).html() } } - //Weather + // Weather if (!found && $('.g>.e>h3', body).length > 0) { - - found = $('.g>.e>h3', body).html(); + found = $('.g>.e>h3', body).html() if ($('.wob_t', body).first().length > 0) { - - found += " " + $('.wob_t', body).first().html(); + found += ' ' + $('.wob_t', body).first().html() } if ($('._Lbd', body).length > 0) { - - found += " " + $('._Lbd', body).html(); + found += ' ' + $('._Lbd', body).html() } } - var speechOutputTemp = entities.decode(striptags(found)); + const speechOutputTemp = entities.decode(striptags(found)) - if (speechOutputTemp === "" || typeof speechOutputTemp === undefined) { - return null; + if (speechOutputTemp === '' || typeof speechOutputTemp === undefined) { + return null } - return speechOutputTemp; + return speechOutputTemp } module.exports = { get: google_resp -}; \ No newline at end of file +} diff --git a/skills/fact/index.js b/skills/fact/index.js index 06abdf4..2c1f71e 100644 --- a/skills/fact/index.js +++ b/skills/fact/index.js @@ -1,42 +1,41 @@ -var google = require('./google/'), +let google = require('./google/'), duckduckgo = require('./duckduckgo/'), - wolframalpha = require('./wolframalpha/'); + wolframalpha = require('./wolframalpha/') -var not_found_responses = ["Hmmm I dont seem to know ", "Sorry I couldn't understand ", "My memory banks dont contain "], - resp_functs = [google, duckduckgo, wolframalpha]; +let not_found_responses = ['Hmmm I dont seem to know ', 'Sorry I couldn\'t understand ', 'My memory banks dont contain '], + resp_functs = [google, duckduckgo, wolframalpha] -String.prototype.replaceAll = function(str1, str2, ignore) { - return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2); -}; +String.prototype.replaceAll = function (str1, str2, ignore) { + return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, '\\$&'), (ignore ? 'gi' : 'g')), (typeof (str2) === 'string') ? str2.replace(/\$/g, '$$$$') : str2) +} -function* _intent() { +function * _intent() { return { keywords: ['who is qqqq', 'where is qqqq', 'when did qqqq', 'what is qqqq', '√ ', '-', '+', '%'], module: 'fact' - }; + } } -function* fact_resp(query) { +function * fact_resp(query) { + let fact = null - var fact = null; + for (let i = 0; i < resp_functs.length; i++) { + const response = yield resp_functs[i].get(query) - for (var i = 0; i < resp_functs.length; i++) { - var response = yield resp_functs[i].get(query); - - if (response && response !== "") { - fact = response; - break; + if (response && response !== '') { + fact = response + break } } - if (!fact || fact === "") { - return not_found_responses[Math.floor(Math.random() * not_found_responses.length)] + query; + if (!fact || fact === '') { + return not_found_responses[Math.floor(Math.random() * not_found_responses.length)] + query } - return fact; + return fact } module.exports = { get: fact_resp, intent: _intent -}; \ No newline at end of file +} diff --git a/skills/fact/wolframalpha/index.js b/skills/fact/wolframalpha/index.js index 99e8a91..bb8082c 100644 --- a/skills/fact/wolframalpha/index.js +++ b/skills/fact/wolframalpha/index.js @@ -1,70 +1,70 @@ -'use strict'; +'use strict' -var request = require('co-request'), - parser = require('xml2json'); +let request = require('co-request'), + parser = require('xml2json') -var config = require('../../../config/'), - keys = config.get; +let config = require('../../../config/'), + keys = config.get -function* wlfra_resp(query) { - var url = 'http://api.wolframalpha.com/v2/query?input=&appid=' + keys.wolframalpha.key; +function * wlfra_resp(query) { + const url = 'http://api.wolframalpha.com/v2/query?input=&appid=' + keys.wolframalpha.key - var data = yield request(url.replace('', query)); + let data = yield request(url.replace('', query)) try { - data = JSON.parse(parser.toJson(data.body)); + data = JSON.parse(parser.toJson(data.body)) } catch (e) { if (e) { - console.log('error parsing wolframalpha body ' + e); + console.log('error parsing wolframalpha body ' + e) } - return null; + return null } - var pods = data.queryresult.pod; + const pods = data.queryresult.pod - var result = ""; + let result = '' try { if (pods && pods.length && pods.length > 0) { for (var i = 0; i < pods.length; i++) { - var index = pods[i]; + var index = pods[i] if (index.primary === 'true') { - result = index.subpod.plaintext; - break; + result = index.subpod.plaintext + break } - if (index.id == "Result") { - result = index.subpod.plaintext; - break; + if (index.id == 'Result') { + result = index.subpod.plaintext + break } } - if (result === "") { + if (result === '') { for (var i = 0; i < pods.length; i++) { - var index = pods[i]; + var index = pods[i] - if (index.title == "Basic information") { - result = index.subpod.plaintext; - break; + if (index.title == 'Basic information') { + result = index.subpod.plaintext + break } } } } else { - return null; + return null } if (result.indexOf('|') != -1) { - result = result.replaceAll(' |', ', '); + result = result.replaceAll(' |', ', ') } - return result; + return result } catch (e) { - console.log(e); - return null; + console.log(e) + return null } } module.exports = { get: wlfra_resp -} \ No newline at end of file +} diff --git a/skills/joke/index.js b/skills/joke/index.js index dcd1d74..6adcf4d 100644 --- a/skills/joke/index.js +++ b/skills/joke/index.js @@ -1,20 +1,20 @@ -var request = require('co-request'); +const request = require('co-request') -function * _intent(){ - return {keywords:['tell me a joke','say something funny','make me laugh'], module:'joke'}; +function * _intent() { + return {keywords: ['tell me a joke', 'say something funny', 'make me laugh'], module: 'joke'} } -function * joke_resp(query){ - var joke_url = 'https://api.chucknorris.io/jokes/random'; +function * joke_resp(query) { + const joke_url = 'https://api.chucknorris.io/jokes/random' - var data = yield request(joke_url); + let data = yield request(joke_url) - data = JSON.parse(data.body); + data = JSON.parse(data.body) - return data.value; + return data.value } module.exports = { - get:joke_resp, - intent:_intent -} \ No newline at end of file + get: joke_resp, + intent: _intent +} diff --git a/skills/movie/index.js b/skills/movie/index.js index 8eeb446..85dccb9 100644 --- a/skills/movie/index.js +++ b/skills/movie/index.js @@ -1,22 +1,22 @@ -var request = require('co-request'); +const request = require('co-request') -function * _intent(){ - return {keywords:['start movie qqqq'], module:'movie'}; +function * _intent() { + return {keywords: ['start movie qqqq'], module: 'movie'} } -function *movie_resp(query){ - var term = query.split(' movie ')[1]; +function * movie_resp(query) { + const term = query.split(' movie ')[1] - var movie_api = 'https://yts.ag/api/v2/list_movies.json?query_term=&sort_by=peers' - - var data = yield request(movie_api.replace('', term)); + const movie_api = 'https://yts.ag/api/v2/list_movies.json?query_term=&sort_by=peers' - data = JSON.parse(data.body); + let data = yield request(movie_api.replace('', term)) - return data.data.movies[0].torrents[0].url; + data = JSON.parse(data.body) + + return data.data.movies[0].torrents[0].url } module.exports = { - get:movie_resp, - intent:_intent -} \ No newline at end of file + get: movie_resp, + intent: _intent +} diff --git a/skills/news/index.js b/skills/news/index.js index b281333..eedbd80 100644 --- a/skills/news/index.js +++ b/skills/news/index.js @@ -1,50 +1,49 @@ -var request = require('co-request'); -var config = require('../../config'); -var keys = config.get; +const request = require('co-request') +const config = require('../../config') +const keys = config.get -function* _intent() { +function * _intent() { return { keywords: ['news'], module: 'news' - }; + } } -function* news_resp(query) { - - var source = 'bbc-news'; +function * news_resp(query) { + let source = 'bbc-news' if (query.indexOf('tech') != -1) { - source = 'the-verge'; + source = 'the-verge' } else if (query.indexOf('sport') != -1) { - source = 'bbc-sport'; + source = 'bbc-sport' } else if (query.indexOf('science') != -1) { - source = 'new-scientist'; + source = 'new-scientist' } else if (query.indexOf('business') != -1) { - source = 'bloomberg'; + source = 'bloomberg' } - var news_url = 'https://newsapi.org/v1/articles?sortBy=latest&apiKey=' + keys.newsapi.key + '&source=' + source; + let news_url = 'https://newsapi.org/v1/articles?sortBy=latest&apiKey=' + keys.newsapi.key + '&source=' + source if (source == 'bbc-news' || source == 'bbc-sport' || source == 'new-scientist' || source == 'bloomberg') { - news_url = news_url.replace('latest', 'top'); + news_url = news_url.replace('latest', 'top') } - var data = yield request(news_url); + let data = yield request(news_url) - data = JSON.parse(data.body); + data = JSON.parse(data.body) - var resp = data.articles; + const resp = data.articles - var item = resp[Math.floor(Math.random() * resp.length)]; + const item = resp[Math.floor(Math.random() * resp.length)] if (item.title.toUpperCase() != item.description.toUpperCase()) { - return item.title + '. ' + item.description; + return item.title + '. ' + item.description } else { - return item.title + '.'; + return item.title + '.' } } module.exports = { get: news_resp, intent: _intent -}; \ No newline at end of file +} diff --git a/skills/shuttlelaunch/index.js b/skills/shuttlelaunch/index.js index 613690e..ab9a674 100644 --- a/skills/shuttlelaunch/index.js +++ b/skills/shuttlelaunch/index.js @@ -1,30 +1,30 @@ -'use strict'; +'use strict' -var request = require('co-request'); +const request = require('co-request') -function* _intent() { +function * _intent() { return { keywords: ['space', 'shuttle', 'launch'], module: 'shuttlelaunch' - }; + } } -function* shuttle_resp(query) { - var shuttle_url = 'https://launchlibrary.net/1.2/launch', +function * shuttle_resp(query) { + let shuttle_url = 'https://launchlibrary.net/1.2/launch', options = { url: shuttle_url, headers: { 'User-Agent': 'P-Brain.ai Shuttle Skill' } - }; - var data = yield request(options); - data = JSON.parse(data.body); - var resp = data.launches[0]; - var resp_string = 'The next launch will be the ' + resp.name + ' on ' + resp.net.split(',')[0] + '.'; - return resp_string; + } + let data = yield request(options) + data = JSON.parse(data.body) + const resp = data.launches[0] + const resp_string = 'The next launch will be the ' + resp.name + ' on ' + resp.net.split(',')[0] + '.' + return resp_string } module.exports = { get: shuttle_resp, intent: _intent -}; \ No newline at end of file +} diff --git a/skills/song/index.js b/skills/song/index.js index 0544834..29fbc86 100644 --- a/skills/song/index.js +++ b/skills/song/index.js @@ -1,31 +1,30 @@ -var yt = require('./youtube'); +const yt = require('./youtube') -function* _intent() { +function * _intent() { return { keywords: ['play qqqq by qqqq', 'play qqqq'], module: 'song' - }; + } } -function* song_resp(query) { - - query = query.replace('play', ''); +function * song_resp(query) { + query = query.replace('play', '') - var track = query.split('by')[0].trim(); - var artist = query.split('by')[1]; + const track = query.split('by')[0].trim() + let artist = query.split('by')[1] if (!artist || artist === '') { - artist = ''; + artist = '' } else { - artist = artist.trim(); + artist = artist.trim() } - var url = yield yt.get(track, artist); + const url = yield yt.get(track, artist) - return url; + return url } module.exports = { get: song_resp, intent: _intent -}; \ No newline at end of file +} diff --git a/skills/time/index.js b/skills/time/index.js index affd435..cec3779 100644 --- a/skills/time/index.js +++ b/skills/time/index.js @@ -1,15 +1,15 @@ -function * _intent(){ - return {keywords:['what time is it','what is the time'], module:'time'}; +function * _intent() { + return {keywords: ['what time is it', 'what is the time'], module: 'time'} } -function * time_resp(query){ - var time = new Date().toLocaleTimeString('en-GB', { hour: "numeric", - minute: "numeric"}); +function * time_resp(query) { + const time = new Date().toLocaleTimeString('en-GB', {hour: 'numeric', + minute: 'numeric'}) - return "It is " + time; + return 'It is ' + time } module.exports = { - get: time_resp, - intent:_intent -} \ No newline at end of file + get: time_resp, + intent: _intent +} diff --git a/skills/timer/index.js b/skills/timer/index.js index fab782d..c241d64 100644 --- a/skills/timer/index.js +++ b/skills/timer/index.js @@ -1,30 +1,30 @@ -var WtoN = require('words-to-num'); +const WtoN = require('words-to-num') -function * _intent(){ - return {keywords:['set timer','set timer for qqqq'], module:'timer'}; +function * _intent() { + return {keywords: ['set timer', 'set timer for qqqq'], module: 'timer'} } -function * timer_resp(query){ - var time_to_set = query.split('for ')[1]; +function * timer_resp(query) { + const time_to_set = query.split('for ')[1] - var number = time_to_set.split(' ')[0]; + let number = time_to_set.split(' ')[0] - if (!number){ - number = time_to_set; - } + if (!number) { + number = time_to_set + } - number = WtoN.convert(number); + number = WtoN.convert(number) - var unit = time_to_set.split(' ')[1]; + const unit = time_to_set.split(' ')[1] - if (number){ - return ':timer: ' +number+' '+unit; - } else { - return 'Sorry, I dont understand '+query; - } + if (number) { + return ':timer: ' + number + ' ' + unit + } else { + return 'Sorry, I dont understand ' + query + } } module.exports = { - get: timer_resp, - intent: _intent -} \ No newline at end of file + get: timer_resp, + intent: _intent +} diff --git a/skills/weather/index.js b/skills/weather/index.js index 0b8833d..89dc4c0 100644 --- a/skills/weather/index.js +++ b/skills/weather/index.js @@ -1,176 +1,173 @@ -var request = require('co-request'); -var config = require('../../config'); -var keys = config.get; +const request = require('co-request') +const config = require('../../config') +const keys = config.get -var api_opnw = 'http://api.openweathermap.org/data/2.5/weather?q=&units=metric&appid=' + keys.openweathermap.key; -var api_opnw_in = 'http://api.openweathermap.org/data/2.5/weather?appid=' + keys.openweathermap.key + '&units=metric&q='; -var api_opnw_on = 'http://api.openweathermap.org/data/2.5/forecast?appid=' + keys.openweathermap.key + '&units=metric&q='; +const api_opnw = 'http://api.openweathermap.org/data/2.5/weather?q=&units=metric&appid=' + keys.openweathermap.key +const api_opnw_in = 'http://api.openweathermap.org/data/2.5/weather?appid=' + keys.openweathermap.key + '&units=metric&q=' +const api_opnw_on = 'http://api.openweathermap.org/data/2.5/forecast?appid=' + keys.openweathermap.key + '&units=metric&q=' -function* _intent() { +function * _intent() { return { keywords: ['what is the weather', 'whats it like in qqqq', 'temperature'], module: 'weather' - }; + } } function get_index_from_day() { - var d = new Date(); - var n = d.getDay(); - return n; + const d = new Date() + const n = d.getDay() + return n } -function* get_country() { - var country_res = yield request('http://ipinfo.io'); +function * get_country() { + let country_res = yield request('http://ipinfo.io') - country_res = JSON.parse(country_res.body); + country_res = JSON.parse(country_res.body) - var loc_string = country_res.city + "," + country_res.country; + const loc_string = country_res.city + ',' + country_res.country - return loc_string.toLowerCase(); + return loc_string.toLowerCase() } function get_new_day_index(forcasted_day) { - var new_index; + let new_index if (forcasted_day.toUpperCase().trim() == 'MONDAY') { - return 1; + return 1 } else if (forcasted_day.toUpperCase().trim() == 'TUESDAY') { - return 2; + return 2 } else if (forcasted_day.toUpperCase().trim() == 'WEDNESDAY') { - return 3; + return 3 } else if (forcasted_day.toUpperCase().trim() == 'THURSDAY') { - return 4; + return 4 } else if (forcasted_day.toUpperCase().trim() == 'FRIDAY') { - return 5; + return 5 } else if (forcasted_day.toUpperCase().trim() == 'SATURDAY') { - return 6; + return 6 } else { - return 7; + return 7 } } -function* weather_resp(query) { - - var res; - var country; - var index; +function * weather_resp(query) { + let res + let country + let index - var forcast = false; - var current_loc = yield get_country(); + let forcast = false + let current_loc = yield get_country() if (!current_loc || current_loc == '') { - current_loc = 'dublin'; + current_loc = 'dublin' } - if (query.indexOf(' in ') != -1) { - country = query.split(' in ')[1]; + country = query.split(' in ')[1] if (country && country != '') { res = yield request(api_opnw_in + country, { - 'headers': { + headers: { 'Content-type': 'application/json' } - }); + }) } else { res = yield request(api_opnw.replace('', current_loc), { - 'headers': { + headers: { 'Content-type': 'application/json' } - }); + }) } } else if (query.indexOf(' for ') != -1 || query.indexOf(' on ') != -1) { - country = query.split(' on ')[1]; + country = query.split(' on ')[1] - forcast = true; + forcast = true if (!country) { - country = query.split(' for ')[1]; + country = query.split(' for ')[1] } if (country.indexOf(' tomorrow') != -1) { - index = get_index_from_day() + 1; + index = get_index_from_day() + 1 } else { - index = get_index_from_day(country); + index = get_index_from_day(country) } - res = yield request(api_opnw_on + current_loc, { - 'headers': { + headers: { 'Content-type': 'application/json' } - }); + }) - forcast = true; + forcast = true } else if (query.indexOf(' tomorrow') != -1) { - index = get_index_from_day() + 1; - forcast = true; + index = get_index_from_day() + 1 + forcast = true res = yield request(api_opnw_on + current_loc, { - 'headers': { + headers: { 'Content-type': 'application/json' } - }); + }) } else { res = yield request(api_opnw.replace('', current_loc), { - 'headers': { + headers: { 'Content-type': 'application/json' } - }); + }) } - res = JSON.parse(res.body); + res = JSON.parse(res.body) - var weather_cond; - var temp; - var condition; - var message; + let weather_cond + let temp + let condition + let message if (forcast) { - weather_cond = res.list[index]; - temp = Math.floor(res.list[index].main.temp).toString() + '°'; - condition = weather_cond.weather[0].main; + weather_cond = res.list[index] + temp = Math.floor(res.list[index].main.temp).toString() + '°' + condition = weather_cond.weather[0].main } else { - weather_cond = res.weather[0]; - temp = Math.floor(res.main.temp).toString() + '°'; - condition = weather_cond.main; + weather_cond = res.weather[0] + temp = Math.floor(res.main.temp).toString() + '°' + condition = weather_cond.main } if (condition == 'Clear') { - message = 'It is currently and '; + message = 'It is currently and ' } else { - message = 'It is currently with '; + message = 'It is currently with ' } if (forcast) { - message = message.replace('It is currently', 'It will be'); + message = message.replace('It is currently', 'It will be') } - var weather = message.replace('', temp); - weather = weather.replace('', condition); + let weather = message.replace('', temp) + weather = weather.replace('', condition) if (country && country != '' && !forcast) { - weather = weather + ' in ' + country; + weather = weather + ' in ' + country } else if (country && country != '' && forcast) { if (country.trim() != 'tomorrow') { - weather = weather + ' on ' + country; + weather = weather + ' on ' + country } } if (query.indexOf('tomorrow') != -1 && weather.indexOf('tomorrow') == -1) { - weather = weather + " tomorrow"; + weather += ' tomorrow' } if (query.indexOf('temperature') != -1 && weather.indexOf('and') != -1) { - var con_string = ' and ' + condition; - weather = weather.replace(con_string, ''); + var con_string = ' and ' + condition + weather = weather.replace(con_string, '') } else if (query.indexOf('temperature') != -1) { - var con_string = ' with ' + condition; - weather = weather.replace(con_string, ''); + var con_string = ' with ' + condition + weather = weather.replace(con_string, '') } - return weather; + return weather } module.exports = { get: weather_resp, intent: _intent -}; \ No newline at end of file +} -- knotmirror 0.0.1 From 41e648613f234dd4ef7e90774c38cd962c23c66f Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 21:16:00 +0100 Subject: [PATCH 3/8] ignore log files --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 63746a6..01ebd67 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ node_modules/ .python-version /log/log.json /config/index.js +/log/responses.json -- knotmirror 0.0.1 From a7fe4bfccec78b6e6c8a4a3216b60a9ff22be8db Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 21:22:05 +0100 Subject: [PATCH 4/8] style --- api/core-ask.js | 101 ++++++++++++++---------------- skills/fact/wolframalpha/index.js | 6 +- 2 files changed, 50 insertions(+), 57 deletions(-) diff --git a/api/core-ask.js b/api/core-ask.js index 2b48df3..1ab624d 100644 --- a/api/core-ask.js +++ b/api/core-ask.js @@ -1,86 +1,81 @@ -var natural = require('natural'), +let natural = require('natural'), classifier = new natural.BayesClassifier(), co = require('co'), speakeasy = require('speakeasy-nlp'), fs = require('fs'), genify = require('thunkify-wrap').genify, - path = require('path'); + path = require('path') -var response = require('../response'), - log = require('../log'); +let response = require('../response'), + log = require('../log') -natural.BayesClassifier.load = genify(natural.BayesClassifier.load); +natural.BayesClassifier.load = genify(natural.BayesClassifier.load) -function getDirectories(srcpath) { - return fs.readdirSync(srcpath).filter(function(file) { - return fs.statSync(path.join(srcpath, file)).isDirectory(); - }); -} +const getDirectories = (srcpath) => + fs.readdirSync(srcpath).filter(file => + fs.statSync(path.join(srcpath, file)).isDirectory()) function * train_recognizer() { - 'use strict'; - - var skills_dir = __dirname+'/skills/'; - skills_dir = skills_dir.replace('/api',''); + let skills_dir = __dirname + '/skills/' + skills_dir = skills_dir.replace('/api', '') - var dirs = getDirectories(skills_dir); + const dirs = getDirectories(skills_dir) - classifier = yield natural.BayesClassifier.load('./api/classifier.json',null); + classifier = yield natural.BayesClassifier.load('./api/classifier.json', null) - for (var i = 0; i 0.25) { - throw 'error'; - return; - } + if (confidence > 0.25) { + throw 'error' + return + } - yield log.add(q); + yield log.add(q) - var intent_breakdown = speakeasy.classify(q); + const intent_breakdown = speakeasy.classify(q) - intent_breakdown.responseType = result.label; - intent_breakdown.originalQuery = q; + intent_breakdown.responseType = result.label + intent_breakdown.originalQuery = q - var resp = yield response.get(intent_breakdown); + var resp = yield response.get(intent_breakdown) - yield log.response(q,resp,result.label); + yield log.response(q, resp, result.label) - var response_obj = { - msg: resp, - type: result.label, - question: q - } + const response_obj = { + msg: resp, + type: result.label, + question: q + } - return response_obj; + return response_obj } -co(function*() { - yield train_recognizer(); -}).catch(function(err) { - console.log(err); - throw err; -}); +co(function * () { + yield train_recognizer() +}).catch(err => { + console.log(err) + throw err +}) module.exports = { - query: _query + query: _query } diff --git a/skills/fact/wolframalpha/index.js b/skills/fact/wolframalpha/index.js index bb8082c..ae44403 100644 --- a/skills/fact/wolframalpha/index.js +++ b/skills/fact/wolframalpha/index.js @@ -1,7 +1,5 @@ -'use strict' - -let request = require('co-request'), - parser = require('xml2json') +const request = require('co-request') +const parser = require('xml2json') let config = require('../../../config/'), keys = config.get -- knotmirror 0.0.1 From 96507708df6b251ea5115bbbb2b71f68abb2ef99 Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 21:23:05 +0100 Subject: [PATCH 5/8] shuttle launch --- skills/shuttlelaunch/index.js | 2 -- skills/song/youtube/index.js | 27 +++++++++++++-------------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/skills/shuttlelaunch/index.js b/skills/shuttlelaunch/index.js index ab9a674..24370fc 100644 --- a/skills/shuttlelaunch/index.js +++ b/skills/shuttlelaunch/index.js @@ -1,5 +1,3 @@ -'use strict' - const request = require('co-request') function * _intent() { diff --git a/skills/song/youtube/index.js b/skills/song/youtube/index.js index c0b3ddc..de2c623 100644 --- a/skills/song/youtube/index.js +++ b/skills/song/youtube/index.js @@ -1,29 +1,28 @@ -var request = require('co-request'); +const request = require('co-request') -function* yt(title, artist) { +function * yt(title, artist) { + title = title.replace(/[^\w\s]/gi, '') + artist = artist.replace(/[^\w\s]/gi, '') - title = title.replace(/[^\w\s]/gi, ''); - artist = artist.replace(/[^\w\s]/gi, ''); - - var url = 'https://www.googleapis.com/youtube/v3/search?q=' + title + ' ' + artist + '&part=snippet&maxResults=10&order=relevance&type=video&key=AIzaSyDY53lC9729bLz26TfKXYKINoYLLZOn0A8'; + const url = 'https://www.googleapis.com/youtube/v3/search?q=' + title + ' ' + artist + '&part=snippet&maxResults=10&order=relevance&type=video&key=AIzaSyDY53lC9729bLz26TfKXYKINoYLLZOn0A8' try { - var data = yield request(url); + let data = yield request(url) - data = JSON.parse(data.body); + data = JSON.parse(data.body) if (!data || !data.items || !data.items.length || !data.items[0]) { - return null; + return null } else { - return 'https://www.youtube.com/watch?v=' + data.items[0].id.videoId; + return 'https://www.youtube.com/watch?v=' + data.items[0].id.videoId } } catch (e) { - console.log(e); - return null; + console.log(e) + return null } - return null; + return null } module.exports = { get: yt -} \ No newline at end of file +} -- knotmirror 0.0.1 From 88932556dc51621dda1e3e0f3d2a9fc63ccac40b Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 21:52:27 +0100 Subject: [PATCH 6/8] services status --- server.js | 1 + skills/status/index.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 skills/status/index.js diff --git a/server.js b/server.js index 7414433..f31a8f8 100644 --- a/server.js +++ b/server.js @@ -31,6 +31,7 @@ app.use((req, res, next) => { app.use(express.static('./src')) +// TODO parse services in query app.get('/api/ask', wrap(function *(req, res) { const input = req.query.q.toLowerCase() diff --git a/skills/status/index.js b/skills/status/index.js new file mode 100644 index 0000000..4ab8da0 --- /dev/null +++ b/skills/status/index.js @@ -0,0 +1,28 @@ +const request = require('co-request') + +const intent = () => ({ + keywords: ['what is status', 'what is the status', 'check status', 'what is the status of qqqq', 'web api'], + module: 'status' +}) + +// where i pee +// happy +// web copy + +function * get(query) { + console.log(query) + + const serviceUrl = 'https://web-api.migros.ch/isalive' + + let data = yield request(serviceUrl) + + const { status } = JSON.parse(data.body) + + return status +} + +module.exports = { + get, + intent +} + -- knotmirror 0.0.1 From fa2fdd0d13fd8d86fc20c94d97834c76ccedc602 Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 22:08:16 +0100 Subject: [PATCH 7/8] ignore more --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 01ebd67..82506d1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ node_modules/ /log/log.json /config/index.js /log/responses.json +/api/classifier.json -- knotmirror 0.0.1 From 4a5cf66ff03b104558d3bb991cf822319b274531 Mon Sep 17 00:00:00 2001 From: "syzer3@gmail.com" Date: Fri, 27 Jan 2017 23:04:43 +0100 Subject: [PATCH 8/8] style --- log/index.js | 6 ------ skills/shuttlelaunch/index.js | 15 ++++++--------- skills/weather/index.js | 19 ++++++++----------- src/js/resp_types.js | 1 - 4 files changed, 14 insertions(+), 27 deletions(-) diff --git a/log/index.js b/log/index.js index abede10..3ecf424 100644 --- a/log/index.js +++ b/log/index.js @@ -1,5 +1,3 @@ -'use strict' - const fs = require('co-fs') function * log_query(query) { @@ -13,8 +11,6 @@ function * log_query(query) { queries_obj.queries = queries yield fs.writeFile('./log/log.json', JSON.stringify(queries_obj, null, 4)) - - return } function * log_response(query, response, skill) { @@ -28,8 +24,6 @@ function * log_response(query, response, skill) { responses_obj.responses = responses yield fs.writeFile('./log/responses.json', JSON.stringify(responses_obj, null, 4)) - - return } function * get_last_query() { diff --git a/skills/shuttlelaunch/index.js b/skills/shuttlelaunch/index.js index 24370fc..be4f8f6 100644 --- a/skills/shuttlelaunch/index.js +++ b/skills/shuttlelaunch/index.js @@ -1,11 +1,9 @@ const request = require('co-request') -function * _intent() { - return { - keywords: ['space', 'shuttle', 'launch'], - module: 'shuttlelaunch' - } -} +const intent = () => ({ + keywords: ['space', 'shuttle', 'launch'], + module: 'shuttlelaunch' +}) function * shuttle_resp(query) { let shuttle_url = 'https://launchlibrary.net/1.2/launch', @@ -18,11 +16,10 @@ function * shuttle_resp(query) { let data = yield request(options) data = JSON.parse(data.body) const resp = data.launches[0] - const resp_string = 'The next launch will be the ' + resp.name + ' on ' + resp.net.split(',')[0] + '.' - return resp_string + return 'The next launch will be the ' + resp.name + ' on ' + resp.net.split(',')[0] + '.' } module.exports = { get: shuttle_resp, - intent: _intent + intent } diff --git a/skills/weather/index.js b/skills/weather/index.js index 89dc4c0..74f11b0 100644 --- a/skills/weather/index.js +++ b/skills/weather/index.js @@ -6,17 +6,14 @@ const api_opnw = 'http://api.openweathermap.org/data/2.5/weather?q=&units const api_opnw_in = 'http://api.openweathermap.org/data/2.5/weather?appid=' + keys.openweathermap.key + '&units=metric&q=' const api_opnw_on = 'http://api.openweathermap.org/data/2.5/forecast?appid=' + keys.openweathermap.key + '&units=metric&q=' -function * _intent() { - return { - keywords: ['what is the weather', 'whats it like in qqqq', 'temperature'], - module: 'weather' - } -} +const intent = () => ({ + keywords: ['what is the weather', 'whats it like in qqqq', 'temperature'], + module: 'weather' +}) function get_index_from_day() { const d = new Date() - const n = d.getDay() - return n + return d.getDay() } function * get_country() { @@ -48,7 +45,7 @@ function get_new_day_index(forcasted_day) { } } -function * weather_resp(query) { +function * weatherResp(query) { let res let country let index @@ -168,6 +165,6 @@ function * weather_resp(query) { } module.exports = { - get: weather_resp, - intent: _intent + get: weatherResp, + intent } diff --git a/src/js/resp_types.js b/src/js/resp_types.js index 5b1a9dc..4628246 100644 --- a/src/js/resp_types.js +++ b/src/js/resp_types.js @@ -51,7 +51,6 @@ recognition.lang = "en-GB"; recognition.onresult = function(event) { - var inputString = event.results['0']['0'].transcript; var yes_input = inputString.slice(0, 3);