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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
-
|
|
!
-
|
!
-
|
|
!
-
-
-
|
|
|
!
!
!
-
|
|
-
|
|
|
|
!
-
-
|
!
-
|
|
|
!
-
|
!
-
|
!
-
-
|
-
|
-
|
-
|
-
|
-
|
-
|
-
-
-
|
!
!
!
!
-
|
|
|
-
-
|
!
!
!
!
-
|
|
|
|
|
!
-
|
|
|
|
-
|
|
|
-
|
!
|
-
|
|
|
|
!
-
-
!
|
|
!
!
| 'use strict';
var Alexa = require('alexa-sdk');
var APP_ID = undefined;
const languageStrings = {
"ja": { translation: {
HELP_MESSAGE: "このスキルは、グーグル検索をするスキルです。",
HELP_REPROMPT: "何を検索しますか?",
STOP_MESSAGE: "スキルを終了します。",
},
},
};
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
var handlers = {
'LaunchRequest': function () {
this.emit('GoogleSearchIntent');
},
'AMAZON.HelpIntent': function () {
var speechOutput = this.t('HELP_MESSAGE');
var reprompt = this.t('HELP_REPROMPT');
this.emit(':ask', speechOutput, reprompt);
},
'AMAZON.CancelIntent': function () {
this.emit(':tell', this.t('STOP_MESSAGE'));
},
'AMAZON.StopIntent': function () {
this.emit(':tell', this.t('STOP_MESSAGE'));
},
"GoogleSearchIntent": function() {
let word='';
if( typeof( this.event.request.intent.slots ) == 'undefined') {
word='slotsがありません';
} else if( typeof( this.event.request.intent ) == 'undefined') {
word='intentがありません';
} else if( typeof( this.event.request ) == 'undefined') {
word='requestがありません';
} else if( typeof( this.event ) == 'undefined') {
word='eventがありません';
} else if( typeof( this ) == 'undefined') {
word='thisがありません';
} else {
let slots = this.event.request.intent.slots;
for( var key in slots) {
if( slots.hasOwnProperty(key) ) {
if ( ""+slots[key].value != 'undefined' ){
word = "" + slots[key].value;
}
}
}
}
if( word.length==0 ){
word = '検索対象が不明です';
const speechOutput = this.t(word);
this.emit(":tell", speechOutput);
} else {
getJson(this, word);
}
}
};
exports.handler = function (event, context) {
const alexa = Alexa.handler(event, context);
alexa.resources = languageStrings; alexa.registerHandlers(handlers); alexa.execute(); };
function getJson(obj, word) {
let result = '何も得られませんでした';
let https = require('https');
const URL = 'https://www.googleapis.com/customsearch/v1?key={API KEY}&cx={SEARCH ENGINE ID}&q=' + encodeURIComponent(word);
https.get(URL, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', (res) => {
res = JSON.parse(body);
result = res['items'][0]['snippet'];
const speechOutput = obj.t(word+'についてお答えします。'+result);
obj.emit(":tell", speechOutput);
});
}).on('error', (e) => {
result = 'JSONを取得できませんでした';
const speechOutput = obj.t(result);
obj.emit(":tell", speechOutput);
});
}
|