Guest User

node.js (Alexa Google Search DE)

a guest
Jan 20th, 2017
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // This skill reuses elements from the Adrian Smart Assistant project
  2. // https://github.com/TheAdrianProject/AdrianSmartAssistant/blob/master/Modules/Google/Google.js
  3.  
  4. 'use strict';
  5.  
  6. var AlexaSkill = require('./AlexaSkill');
  7. var rp = require('request-promise');
  8. var $ = require('cheerio');
  9. var Entities = require('html-entities').XmlEntities;
  10. var entities = new Entities();
  11. var striptags = require('striptags');
  12. var tabletojson = require('tabletojson');
  13. var xray = require('x-ray')();
  14. var json2csv = require('json2csv');
  15.  
  16. var APP_ID = undefined; //replace with 'amzn1.echo-sdk-ams.app.[your-unique-value-here]';
  17.  
  18. var AlexaGoogleSearch = function() {
  19.     AlexaSkill.call(this, APP_ID);
  20. }
  21.  
  22. AlexaGoogleSearch.prototype = Object.create(AlexaSkill.prototype);
  23. AlexaGoogleSearch.prototype.constructor = AlexaGoogleSearch;
  24.  
  25. AlexaGoogleSearch.prototype.eventHandlers.onLaunch = function(launchRequest, session, response) {
  26.     console.log("AlexaGoogleSearch onLaunch requestId" + launchRequest.requestId + ", sessionId: " + session.sessionId);
  27.     var speechOutput = "Willkommen zur Google Suche. Wonach suchst Du?";
  28.     var repromptText = "";
  29.     response.ask(speechOutput, repromptText);
  30. }
  31.  
  32. AlexaGoogleSearch.prototype.intentHandlers = {
  33.     "SearchIntent": function(intent, session, response) {
  34.         var query = intent.slots.search.value;
  35.        
  36.         // Title for Alexa app card
  37.         var cardTitle = ("Google Suchergebnisse für: " + query);
  38.        
  39.         // Remove spaces and replace with +
  40.         query = query.replace(" ","+");
  41.        
  42.         // Remove _ and replace with +
  43.         query = query.replace(/ /g ,"+");
  44.        
  45.         var speechOutput = "Fehler";
  46.        
  47.         // Parsing routine modified from
  48.         // https://github.com/TheAdrianProject/AdrianSmartAssistant/blob/master/Modules/Google/Google.js        
  49.  
  50.         //parse queries
  51.        
  52.         // create userAgent string from a number of selections
  53.        
  54.         var userAgent = [
  55.             'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
  56.             'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
  57.             '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',
  58.             'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0',
  59.             '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'
  60.             ];
  61.        
  62.         var sel = Math.floor((Math.random() * 5) );
  63.         var userAgentRandom = userAgent[sel];
  64.        
  65.         console.log("User Agent: - " + userAgentRandom);
  66.        
  67.         // Create search sring
  68.         var queryString = "http://www.google.de/search?q=" + query + '&oe=utf8&hl=de';
  69.        
  70.         var options = {
  71.             uri: queryString,
  72.             'User-Agent': userAgentRandom
  73.         }
  74.        
  75.         rp(options)
  76.             .then(function(body) {
  77.                 console.log("Running parsing");
  78.                 console.log("Search string is:" + queryString);
  79.                 console.log("HTML is:" + $("#ires",body).html());
  80.                                
  81.             // result variable init
  82.             var found = 0;
  83.        
  84. //          if (!found && $('._m3b',body).length>0){
  85. //                console.log("Don't know")
  86. //              found = $('._m3b',body).html()
  87.                        
  88. //          }
  89.             //how many 2
  90.             if (!found ){
  91.                 //how many
  92.                 var items = $('._m3b',body).get().length; // find how many lines there are in answer table
  93.        
  94.                 if (items) {
  95.                     console.log( items + " how many 2 answer found");
  96.                     found = $('._eGc',body).html() + ", ";
  97.  
  98.  
  99.                     for (var count = 0; count < items; count++) {  
  100.                         found = found + $('._m3b',body).eq(count).html() + ", ";
  101.                     }
  102.                 }
  103.             }
  104.  
  105.                                     //name list
  106.             if (!found && $('#_vBb',body).length>0){
  107.  
  108.                 found = $('#_vBb',body).html();
  109.                 console.log("Found name list");
  110.             }
  111.  
  112.             //facts 1
  113.             if (!found && $('._tXc>span',body).length>0){
  114.  
  115.                 found = $('._tXc>span',body).html();
  116.                 console.log("Found facts 1");
  117.             }
  118.  
  119.             //facts 2
  120.             if (!found && $('._sPg',body).length>0){
  121.  
  122.                 found = " "+$('._sPg',body).html();
  123.                 console.log("Found facts 2");          
  124.             }
  125.        
  126.             //instant + description 1
  127.             if (!found && $('._Oqb',body).length>0){
  128.  
  129.                 found = $('._Oqb',body).html();
  130.                 console.log("Found instant and desc 1");
  131.  
  132.             //how many 1
  133.                 if ( $('._Mqb',body).length>0){
  134.  
  135.                     found+= " "+$('._Mqb',body).html();
  136.                     console.log("Found Found instant and desc 1 - how many");
  137.                 }
  138.             }
  139.             //instant + description 2
  140.             if (!found && $('._o0d',body).length>0){
  141.                
  142.                 console.log("Found Found instant and desc 2")
  143.                 var tablehtml = $('._o0d',body).html()
  144.                
  145.                 found = tablehtml // fallback in case a table isn't found
  146.                
  147.                 xray(tablehtml, ['table@html'])(function (conversionError, tableHtmlList) {
  148.                 if (conversionError) {
  149.                   console.log("Xray conversionError");
  150.                 }
  151.                 if (tableHtmlList){
  152.                   // xray returns the html inside each table tag, and tabletojson
  153.                   // expects a valid html table, so we need to re-wrap the table.
  154.                   var table1 = tabletojson.convert('<table>' + tableHtmlList[0]+ '</table>');
  155.                    console.log(table1)
  156.                    
  157.                    var csv = json2csv({data: table1, hasCSVColumnTitle: false })
  158.                    
  159.                    csv = csv.replace(/(['"])/g, "") //get rid of double quotes
  160.                        csv = csv.replace(/\,(.*?)\:/g, ", ") //get rid column names
  161.                        csv = csv.replace(/\{(.*?)\:/g, ", ") //get rid column names
  162.                        csv = csv.replace(/([}])/g, " ALEXAPAUSE ") //get rid of } and add a pause which will be replaced with SSML later
  163.                                
  164.                     found = csv.toString();
  165.                    
  166.                 }
  167.  
  168.                
  169.               });
  170.             }
  171.  
  172.             //Time, Date
  173.             if (!found && $('._rkc._Peb',body).length>0){
  174.  
  175.                 found = $('._rkc._Peb',body).html();
  176.                 console.log("Found date and Time");
  177.                                
  178.             }
  179.             //Maths
  180.             if (!found && $('.nobr>.r',body).length>0){
  181.                 found = $('.nobr>.r',body).html();
  182.                 console.log("Found maths");                
  183.             }
  184.  
  185.             //simple answer
  186.             if (!found && $('.obcontainer',body).length>0){
  187.                 found = $('.obcontainer',body).html();
  188.                 console.log("Found Simple answer");
  189.                                
  190.             }
  191.  
  192.             //Definition
  193.             if (!found && $('.r>div>span',body).first().length>0){
  194.                 found = $('.r>div>span',body).first().html() +" definition. ";
  195.                 console.log("Found definition");
  196.                 //how many
  197.                 var items = $('.g>div>table>tr>td>ol>li',body).get().length; // find how many lines there are in answer table
  198.                
  199.                 if (items) {
  200.                     console.log( items + " Type 4 answer sections result");
  201.  
  202.                     for (var count = 0; count < items; count++) {  
  203.  
  204.                         found = found + $('.g>div>table>tr>td>ol>li',body).eq(count).html() + ", ";
  205.                     }
  206.                 }
  207.             }
  208.             //TV show
  209.             if (!found && $('._B5d',body).length>0){   
  210.                 found = $('._B5d',body).html();
  211.                 console.log("Found tv show");
  212.                 //how many
  213.                 if ( $('._Pxg',body).length>0){
  214.                     found+= ". "+$('._Pxg',body).html();
  215.                 }
  216.                 //how many
  217.                 if ( $('._tXc',body).length>0){
  218.  
  219.                     found+= ". "+$('._tXc',body).html();
  220.                 }
  221.             }
  222.        
  223.             //Weather
  224.             if (!found && $('.g>.e>h3',body).length>0){
  225.            
  226.                 found = $('.g>.e>h3',body).html();
  227.                 console.log("Found weather");
  228.  
  229.                 //how many
  230.                 if ( $('.wob_t',body).first().length>0){
  231.  
  232.                     found+= " "+ $('.wob_t',body).first().html();
  233.                     console.log("Found weather");
  234.                 }
  235.  
  236.                 //how many
  237.                 if ( $('._Lbd',body).length>0){
  238.  
  239.                     found+= " "+ $('._Lbd',body).html();
  240.                     console.log("Found how many");
  241.                 }
  242.             }
  243.  
  244.             // strip out html tags to leave just text
  245.             var speechOutputTemp = entities.decode(striptags(found));
  246.             var cardOutputText = speechOutputTemp;
  247.             // make sure all full stops have space after them otherwise alexa says the word dot
  248.  
  249.             speechOutputTemp = speechOutputTemp.split('.com').join(" punkt com ") // deal with dot com
  250.             speechOutputTemp = speechOutputTemp.split('.de').join(" punkt d e") // deal with .de
  251.       speechOutputTemp = speechOutputTemp.split('.net').join(" punkt net ") // deal with .net
  252.       speechOutputTemp = speechOutputTemp.split('.org').join(" punkt org ") // deal with .org
  253.       speechOutputTemp = speechOutputTemp.split('a.m').join("am") // deal with a.m
  254.       speechOutputTemp = speechOutputTemp.split('p.m').join("pm") // deal with a.m
  255.      
  256.            
  257.       // deal with decimal places
  258.       speechOutputTemp = speechOutputTemp.replace(/\d[\.]{1,}/g,'\$&DECIMALPOINT')// search for decimal points following a digit and add DECIMALPOINT TEXT
  259.       speechOutputTemp = speechOutputTemp.replace(/.DECIMALPOINT/g,'DECIMALPOINT')// remove decimal point
  260.      
  261.       // deal with characters that are illegal in SSML
  262.      
  263.       speechOutputTemp = speechOutputTemp.replace(/&/g,' und ') // replace ampersands
  264.       speechOutputTemp = speechOutputTemp.replace(/</g,' kleiner als ') // replace < symbol
  265.       speechOutputTemp = speechOutputTemp.replace(/""/g,'') // replace double quotes
  266.                                        
  267.            
  268.       speechOutputTemp = speechOutputTemp.split('ALEXAPAUSE').join('<break time=\"500ms\"/>') // add in SSML pauses at table ends
  269.       cardOutputText = cardOutputText.split('ALEXAPAUSE').join('') // remove pauses from card text
  270.             speechOutputTemp = speechOutputTemp.split('.').join(". <break time=\"250ms\"/>") // Assume any remaining dot are concatonated sentances so turn them into full stops with a pause afterwards
  271.             var speechOutput = speechOutputTemp.replace(/DECIMALPOINT/g,'.') // Put back decimal points
  272.            
  273.                        
  274.             if (speechOutput=="") speechOutput = "Es tut mir Leid. Ich habe keine Antwort gefunden."
  275.            
  276.             // Covert speechOutput into SSML so that pauses can be processed
  277.             var SSMLspeechOutput = {
  278.                 speech: '<speak>' + speechOutput + '</speak>',
  279.                 type: 'SSML'
  280.             };
  281.  
  282.            
  283.             response.tellWithCard(SSMLspeechOutput, cardTitle, cardOutputText);
  284.            
  285.            
  286.  
  287.             //    response.tell(speechOutput)
  288.             }).catch(function(err) {
  289.             console.log("ERROR" + err);
  290.             speechOutput = "Es gab einen Fehler während der Suche.";
  291.             response.tell(speechOutput);
  292.         })
  293.     },
  294.  
  295.     "AMAZON.StopIntent": function(intent, session, response) {
  296.         var speechOutput = "";
  297.         response.tell(speechOutput);
  298.     }
  299. }
  300.  
  301. exports.handler = function(event, context) {
  302.     var AlexaGoogleSearchHelper = new AlexaGoogleSearch();
  303.     AlexaGoogleSearchHelper.execute(event, context);
  304. }
Add Comment
Please, Sign In to add comment