forked from alexa-samples/skill-sample-nodejs-city-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
306 lines (248 loc) · 11.2 KB
/
index.js
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// 1. Text strings =====================================================================================================
// Modify these strings and messages to change the behavior of your Lambda function
const languageStrings = {
'en': {
'translation': {
'WELCOME' : "Welcome to Gloucester Guide!",
'HELP' : "Say about, to hear more about the city, or say coffee, breakfast, lunch, or dinner, to hear local restaurant suggestions, or say recommend an attraction, or say, go outside. ",
'ABOUT' : "Gloucester Massachusetts is a city on the Atlantic Ocean. A popular summer beach destination, Gloucester has a rich history of fishing and ship building.",
'STOP' : "Okay, see you next time!"
}
}
// , 'de-DE': { 'translation' : { 'TITLE' : "Local Helfer etc." } }
};
const data = {
"city" : "Gloucester",
"state" : "MA",
"postcode" : "01930",
"restaurants" : [
{ "name":"Zeke's Place",
"address":"66 East Main Street", "phone": "978-283-0474",
"meals": "breakfast, lunch",
"description": "A cozy and popular spot for breakfast. Try the blueberry french toast!"
},
{ "name":"Morning Glory Coffee Shop",
"address":"25 Western Avenue", "phone": "978-281-1851",
"meals": "coffee, breakfast, lunch",
"description": "A homestyle diner located just across the street from the harbor sea wall."
},
{ "name":"Sugar Magnolias",
"address":"112 Main Street", "phone": "978-281-5310",
"meals": "breakfast, lunch",
"description": "A quaint eatery, popular for weekend brunch. Try the carrot cake pancakes."
},
{ "name":"Seaport Grille",
"address":"6 Rowe Square", "phone": "978-282-9799",
"meals": "lunch, dinner",
"description": "Serving seafood, steak and casual fare. Enjoy harbor views on the deck."
},
{ "name":"Latitude 43",
"address":"25 Rogers Street", "phone": "978-281-0223",
"meals": "lunch, dinner",
"description": "Features artsy decor and sushi specials. Live music evenings at the adjoining Minglewood Tavern."
},
{ "name":"George's Coffee Shop",
"address":"178 Washington Street", "phone": "978-281-1910",
"meals": "coffee, breakfast, lunch",
"description": "A highly rated local diner with generously sized plates."
},
],
"attractions":[
{
"name": "Whale Watching",
"description": "Gloucester has tour boats that depart twice daily from Rogers street at the harbor. Try either the 7 Seas Whale Watch, or Captain Bill and Sons Whale Watch. ",
"distance": "0"
},
{
"name": "Good Harbor Beach",
"description": "Facing the Atlantic Ocean, Good Harbor Beach has huge expanses of soft white sand that attracts hundreds of visitors every day during the summer.",
"distance": "2"
},
{
"name": "Rockport",
"description": "A quaint New England town, Rockport is famous for rocky beaches, seaside parks, lobster fishing boats, and several art studios.",
"distance": "4"
},
{
"name": "Fenway Park",
"description": "Home of the Boston Red Sox, Fenway park hosts baseball games From April until October, and is open for tours. ",
"distance": "38"
}
]
}
const SKILL_NAME = "Gloucester Guide";
// Weather courtesy of the Yahoo Weather API.
// This free API recommends no more than 2000 calls per day
const myAPI = {
host: 'query.yahooapis.com',
port: 443,
path: `/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22${encodeURIComponent(data.city)}%2C%20${data.state}%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys`,
method: 'GET'
};
// 2. Skill Code =======================================================================================================
const Alexa = require('alexa-sdk');
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
// alexa.appId = 'amzn1.echo-sdk-ams.app.1234';
///alexa.dynamoDBTableName = 'YourTableName'; // creates new table for session.attributes
alexa.resources = languageStrings;
alexa.registerHandlers(handlers);
alexa.execute();
};
const handlers = {
'LaunchRequest': function () {
var say = this.t('WELCOME') + ' ' + this.t('HELP');
this.response.speak(say).listen(say);
this.emit(':responseReady');
},
'AboutIntent': function () {
this.response.speak(this.t('ABOUT'));
this.emit(':responseReady');
},
'CoffeeIntent': function () {
var restaurant = randomArrayElement(getRestaurantsByMeal('coffee'));
this.attributes['restaurant'] = restaurant.name;
var say = 'For a great coffee shop, I recommend, ' + restaurant.name + '. Would you like to hear more?';
this.response.speak(say).listen(say);
this.emit(':responseReady');
},
'BreakfastIntent': function () {
var restaurant = randomArrayElement(getRestaurantsByMeal('breakfast'));
this.attributes['restaurant'] = restaurant.name;
var say = 'For breakfast, try this, ' + restaurant.name + '. Would you like to hear more?';
this.response.speak(say).listen(say);
this.emit(':responseReady');
},
'LunchIntent': function () {
var restaurant = randomArrayElement(getRestaurantsByMeal('lunch'));
this.attributes['restaurant'] = restaurant.name;
var say = 'Lunch time! Here is a good spot. ' + restaurant.name + '. Would you like to hear more?';
this.response.speak(say).listen(say);
this.emit(':responseReady');
},
'DinnerIntent': function () {
var restaurant = randomArrayElement(getRestaurantsByMeal('dinner'));
this.attributes['restaurant'] = restaurant.name;
var say = 'Enjoy dinner at, ' + restaurant.name + '. Would you like to hear more?';
this.response.speak(say).listen(say);
this.emit(':responseReady');
},
'AMAZON.YesIntent': function () {
var restaurantName = this.attributes['restaurant'];
var restaurantDetails = getRestaurantByName(restaurantName);
var say = restaurantDetails.name
+ ' is located at ' + restaurantDetails.address
+ ', the phone number is ' + restaurantDetails.phone
+ ', and the description is, ' + restaurantDetails.description
+ ' I have sent these details to the Alexa App on your phone. Enjoy your meal! <say-as interpret-as="interjection">bon appetit</say-as>' ;
var card = restaurantDetails.name + '\n' + restaurantDetails.address + '\n'
+ data.city + ', ' + data.state + ' ' + data.postcode
+ '\nphone: ' + restaurantDetails.phone + '\n';
this.response.cardRenderer(SKILL_NAME, card);
this.response.speak(say);
this.emit(':responseReady');
},
'AttractionIntent': function () {
var distance = 200;
if (this.event.request.intent.slots.distance.value) {
distance = this.event.request.intent.slots.distance.value;
}
var attraction = randomArrayElement(getAttractionsByDistance(distance));
var say = 'Try '
+ attraction.name + ', which is '
+ (attraction.distance == "0" ? 'right downtown. ' : attraction.distance + ' miles away. Have fun! ')
+ attraction.description;
this.response.speak(say);
this.emit(':responseReady');
},
'GoOutIntent': function () {
getWeather( ( localTime, currentTemp, currentCondition) => {
// time format 10:34 PM
// currentTemp 72
// currentCondition, e.g. Sunny, Breezy, Thunderstorms, Showers, Rain, Partly Cloudy, Mostly Cloudy, Mostly Sunny
// sample API URL for Irvine, CA
// https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22irvine%2C%20ca%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
var say = 'It is ' + localTime
+ ' and the weather in ' + data.city
+ ' is '
+ currentTemp + ' and ' + currentCondition;
this.response.speak(say);
this.emit(':responseReady');
// TODO
// Decide, based on current time and weather conditions,
// whether to go out to a local beach or park;
// or recommend a movie theatre; or recommend staying home
});
},
'AMAZON.NoIntent': function () {
this.emit('AMAZON.StopIntent');
},
'AMAZON.HelpIntent': function () {
this.response.speak(this.t('HELP')).listen(this.t('HELP'));
this.emit(':responseReady');
},
'AMAZON.CancelIntent': function () {
this.response.speak(this.t('STOP'));
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
this.emit('SessionEndedRequest');
},
'SessionEndedRequest': function () {
this.response.speak(this.t('STOP'));
this.emit(':responseReady');
}
};
// END of Intent Handlers {} ========================================================================================
// 3. Helper Function =================================================================================================
function getRestaurantsByMeal(mealtype) {
var list = [];
for (var i = 0; i < data.restaurants.length; i++) {
if(data.restaurants[i].meals.search(mealtype) > -1) {
list.push(data.restaurants[i]);
}
}
return list;
}
function getRestaurantByName(restaurantName) {
var restaurant = {};
for (var i = 0; i < data.restaurants.length; i++) {
if(data.restaurants[i].name == restaurantName) {
restaurant = data.restaurants[i];
}
}
return restaurant;
}
function getAttractionsByDistance(maxDistance) {
var list = [];
for (var i = 0; i < data.attractions.length; i++) {
if(parseInt(data.attractions[i].distance) <= maxDistance) {
list.push(data.attractions[i]);
}
}
return list;
}
function getWeather(callback) {
var https = require('https');
var req = https.request(myAPI, res => {
res.setEncoding('utf8');
var returnData = "";
res.on('data', chunk => {
returnData = returnData + chunk;
});
res.on('end', () => {
var channelObj = JSON.parse(returnData).query.results.channel;
var localTime = channelObj.lastBuildDate.toString();
localTime = localTime.substring(17, 25).trim();
var currentTemp = channelObj.item.condition.temp;
var currentCondition = channelObj.item.condition.text;
callback(localTime, currentTemp, currentCondition);
});
});
req.end();
}
function randomArrayElement(array) {
var i = 0;
i = Math.floor(Math.random() * array.length);
return(array[i]);
}