Skip to content

Instantly share code, notes, and snippets.

@rondagdag
Last active May 13, 2016 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondagdag/07739aa1007dd40f3bc5b1955a770947 to your computer and use it in GitHub Desktop.
Save rondagdag/07739aa1007dd40f3bc5b1955a770947 to your computer and use it in GitHub Desktop.
Money Converter for Amazon Echo
/*
Developed by Ron Dagdag
Email: rlyle78@gmail.com
*/
'use strict';
let http = require('http');
var AWS = require("aws-sdk");
const dynamoTableName = "MoneyConverter";
// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
try {
console.log("event.session.application.applicationId=" + event.session.application.applicationId);
/**
* Uncomment this if statement and populate with your skill's application ID to
* prevent someone else from configuring a skill that sends requests to this function.
*/
if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.11111111111111111") {
context.fail("Invalid Application ID");
}
if (event.session.new) {
onSessionStarted({requestId: event.request.requestId}, event.session);
}
if (event.request.type === "LaunchRequest") {
onLaunch(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "IntentRequest") {
onIntent(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "SessionEndedRequest") {
onSessionEnded(event.request, event.session);
context.succeed();
}
} catch (e) {
context.fail("Exception: " + e);
}
};
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId +
", sessionId=" + session.sessionId);
}
/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
console.log("onLaunch requestId=" + launchRequest.requestId +
", sessionId=" + session.sessionId);
// Dispatch to your skill's launch.
getWelcomeResponse(session, callback);
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
console.log("onIntent requestId=" + intentRequest.requestId +
", sessionId=" + session.sessionId);
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
// Dispatch to your skill's intent handlers
if ("BaseCurrencyIntent" === intentName) {
setBaseCurrencyInSession(intent, session, callback);
} else if ("MoneyConvertIntent" === intentName) {
getMoneyConvertFromSession(intent, session, callback);
} else if ("ExchangeRateIntent" === intentName) {
getConversionRateFromSession(intent, session, callback);
} else if ("AMAZON.HelpIntent" === intentName) {
getHelpResponse(session, callback);
} else if ("AMAZON.StopIntent" === intentName || "AMAZON.CancelIntent" === intentName) {
handleSessionEndRequest(callback);
} else {
throw "Invalid intent";
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId +
", sessionId=" + session.sessionId);
// Add cleanup logic here
}
// --------------- Functions that control the skill's behavior -----------------------
function getWelcomeResponse(session, callback) {
// If we wanted to initialize the session to have some attributes we could add those here.
var sessionAttributes = {};
var cardTitle = "Welcome";
var speechOutput = "Money Converter " +
"Please tell me your base currency";
// If the user either does not reply to the welcome message or says something that is not
// understood, they will be prompted again with this text.
var repromptText = "Please tell me your base currency by saying, " +
"my base currency is US dollars then you can ask to convert 100 euros?";
var shouldEndSession = false;
console.log('getItem')
console.log('getItem')
var dynamo = new AWS.DynamoDB.DocumentClient();
var params = {
TableName : dynamoTableName,
Key:{
UserId: session.user.userId
}
};
dynamo.getItem(params, function (err, data) {
if (err) {
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
} else if (data.Item === undefined) {
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
} else {
console.log('creating session attributes');
var basecurrency = data.Item.BaseCurrency
speechOutput = "Money Converter " +
"Your Base Currency is " + basecurrency + " Please ask me to convert 100 euros";
repromptText = "Please ask me to convert 100 euros? ";
sessionAttributes = createBaseCurrencyAttributes(basecurrency);
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
});
}
function getHelpResponse(session, callback) {
// If we wanted to initialize the session to have some attributes we could add those here.
var sessionAttributes = {};
var cardTitle = "Help";
var speechOutput = "Money Converter " +
"Please set your Base Currency then ask me to convert 100 euros then I will convert them for you.";
// If the user either does not reply to the welcome message or says something that is not
// understood, they will be prompted again with this text.
var repromptText = "Money Converter " +
"Please set your Base Currency then ask me to convert 100 euros then I will convert them for you.";
var shouldEndSession = false;
console.log('getItem')
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
function handleSessionEndRequest(callback) {
var cardTitle = "Good Bye";
var speechOutput = "Thank you.";
// Setting this to true ends the session and exits the skill.
var shouldEndSession = true;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}
function setBaseCurrencyInSession(intent, session, callback) {
var cardTitle = "Base Currency Question";
var basecurrencySlot = intent.slots.BaseCurrency;
var repromptText = "";
var sessionAttributes = {};
var shouldEndSession = false;
var speechOutput = "";
if (basecurrencySlot && basecurrencySlot.value != "?") {
var basecurrency = getBaseCurrencyMapping(basecurrencySlot.value);
if (basecurrency == null)
{
speechOutput = "I'm not sure what your base currency is. Please try again";
repromptText = "I'm not sure what your base currency is. You can tell me your " +
"base currency by saying, my currency is US dollars";
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
sessionAttributes = createBaseCurrencyAttributes(basecurrency);
speechOutput = "I now know your base currency is " + getBaseCurrencyConversion(basecurrency) + ". You can ask me " +
"to convert 100 euros?";
repromptText = "You can ask me to convert 100 euros?";
//dynamo.putItem(tableItem);
var dynamo = new AWS.DynamoDB.DocumentClient();
var params = {
TableName : dynamoTableName,
Item:{
UserId: session.user.userId,
BaseCurrency: basecurrency
}
};
dynamo.put(params, function (err, data) {
if (err) {
console.log(err, err.stack);
} else
if (callback) {
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession))
}
});
} else {
speechOutput = "I'm not sure what your base currency is. Please try again";
repromptText = "I'm not sure what your base currency is. You can tell me your " +
"base currency by saying, my base currency is US dollars";
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
//callback(sessionAttributes,
// buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession))
}
function getBaseCurrencyMapping(basecurrency)
{
switch(basecurrency.toLowerCase()) {
case "aud":
case "australian":
case "australia":
case "australian dollars":
case "australian dollar":
return "AUD"
case "bgn":
case "bulgarian lev":
case "bulgarian levs":
case "bulgaria":
case "bulgarian":
return "BGN"
case "brl":
case "brazilian reals":
case "brazilian real":
case "brazil":
case "brazilian":
return "BRL"
case "cad":
case "canadian dollars":
case "canadian dollar":
case "canada":
case "canadian":
return "CAD"
case "chf":
case "swiss francs":
case "swiss franc":
case "franc":
case "swiss dollars":
case "swiss":
return "CHF"
case "cny":
case "chinese yuan":
case "chinese yuans":
case "chinese dollars":
case "yuan":
return "CNY"
case "czk":
case "czech republic koruna":
case "czech republic korunas":
case "koruna":
case "czech":
return "CZK"
case "dkk":
case "danish krones":
case "danish krone":
case "danish":
return "DKK"
case "eur":
case "euro":
case "euros":
return "EUR"
case "gbp":
case "british pound":
case "british pounds":
case "british":
case "pounds":
return "GBP"
case "hkd":
case "hong kong dollars":
case "hong kong dollar":
case "hong kong":
return "HKD"
case "hrk":
case "croatian kuna":
case "croatian kunas":
case "croatia":
return "HRK"
case "huf":
case "hungarian forint":
case "hungarian forints":
case "hungarian":
return "HUF"
case "idr":
case "indonesian rupiah":
case "indonesian rupiahs":
case "rupiah":
case "indonesian":
return "IDR"
case "ils":
case "israeli new sheqel":
case "israeli new sheqels":
case "israeli":
case "sheqel":
return "ILS"
case "inr":
case "indian rupee":
case "indian rupees":
case "indian":
case "rupees":
case "rupee":
return "INR"
case "jpy":
case "japanese yen":
case "japanese yens":
case "yen":
case "japan":
case "japanese":
return "JPY"
case "krw":
case "south korean won":
case "south korean wons":
case "korean won":
case "won":
case "south korean":
return "KRW"
case "mxn":
case "mexican peso":
case "mexican pesos":
case "mexican":
// case "pesos":
// case "peso":
return "MXN"
case "myr":
case "malaysian ringgit":
case "malaysian ringgits":
case "ringgit":
case "malaysian":
return "MYR"
case "nok":
case "norwegian krone":
case "norwegian krones":
case "norwegian":
return "NOK"
case "nzd":
case "new zealand dollar":
case "new zealand dollars":
case "new zealand":
return "NZD"
case "php":
case "philippine peso":
case "philippine pesos":
case "philippines":
case "philippine":
case "pesos":
case "peso":
return "PHP"
case "pln":
case "polish zloty":
case "polish":
case "zloty":
return "PLN"
case "ron":
case "romanian leu":
case "romanian leus":
case "romania":
case "leu":
return "RON"
case "rub":
case "russian ruble":
case "russian rubles":
case "russia":
case "russian":
case "ruble":
case "rubles":
return "RUB"
case "sek":
case "swedish krona":
case "swedish kronas":
case "swedish":
case "krona":
case "kronas":
return "SEK"
case "sgd":
case "singapore dollar":
case "singapore dollars":
case "singapore":
return "SGD"
case "thb":
case "thai baht":
case "thai bahts":
case "thai":
case "baht":
return "THB"
case "try":
case "turkish lira":
case "turkish liras":
case "turkish":
case "lira":
return "TRY"
case "usd":
case "united states dollar":
case "united states dollars":
case "US dollar":
case "dollars":
case "dollar":
return "USD"
case "zar":
case "south african rand":
case "south african rands":
case "south africa":
case "rand":
case "rands":
return "ZAR"
default:
return null
}
}
function createBaseCurrencyAttributes(mybasecurrency) {
return {
BaseCurrency: mybasecurrency
};
}
function getMoneyConvertFromSession(intent, session, callback) {
var basecurrency;
var targetcurrency;
var amount = 0;
var repromptText = null;
var sessionAttributes = {};
var shouldEndSession = false;
var speechOutput = "";
var repNames = "";
var totalReps = 0;
if (session.attributes) {
basecurrency = session.attributes.BaseCurrency;
}
if (intent.slots) {
var baseCurrencySlot = intent.slots.BaseCurrency;
if (baseCurrencySlot && baseCurrencySlot.value){
basecurrency = getBaseCurrencyMapping(baseCurrencySlot.value);
}
var targetCurrencySlot = intent.slots.TargetCurrency;
console.log('target currency :' + targetCurrencySlot)
if (targetCurrencySlot && targetCurrencySlot.value){
console.log('target currency :' + targetCurrencySlot.value)
targetcurrency = getBaseCurrencyMapping(targetCurrencySlot.value);
}
var amountSlot = intent.slots.Amount;
if (amountSlot && amountSlot.value && amountSlot.value > 0){
amount = amountSlot.value;
}
}
console.log('base currency :' + basecurrency)
console.log('target currency :' + targetcurrency)
if (amount == null || amount <= 0)
{
speechOutput = "I'm not sure what the amount is, you can say, how much is 100 dollars";
callback(sessionAttributes,
buildSpeechletResponse("Currency Question", speechOutput, speechOutput, shouldEndSession));
} else
if (targetcurrency == null)
{
speechOutput = "I'm not sure what your target currency is, you can say, how much is 100 dollars";
callback(sessionAttributes,
buildSpeechletResponse("Currency Question", speechOutput, speechOutput, shouldEndSession));
} else
if (basecurrency) {
//http://whoismyrepresentative.com/getall_mems.php?zip=75034
shouldEndSession = true;
getConversion(basecurrency, targetcurrency, function(conversion){
//list all the names of state representative
/*var repList = getAllRepresentativeNames(reps);
repNames = repList.names;
totalReps = repList.total;*/
var targetCurrencyValue = conversion.rates[targetcurrency];
//speechOutput = "It's about " + (amount / conversion.rates[targetcurrency]).toFixed(2) + " " + getBaseCurrencyWords(basecurrency);
speechOutput = "It's about " + (amount / targetCurrencyValue).toFixed(2) + " " + getBaseCurrencyWords(basecurrency) + " for " + amount + " " + getBaseCurrencyWords(targetcurrency);
callback(sessionAttributes,
buildSpeechletResponse("Conversion Result", speechOutput, speechOutput, shouldEndSession));
});
} else {
console.log('getItem')
var dynamo = new AWS.DynamoDB.DocumentClient();
var params = {
TableName : dynamoTableName,
Key:{
UserId: session.user.userId
}
};
dynamo.get(params, function (err, data) {
console.log(err)
console.log(data)
if (err) {
speechOutput = "There's an error. Please try again. you can say, how much is 100 dollars";
callback(sessionAttributes,
buildSpeechletResponse("Base Currency Question", speechOutput, "you can say, how much is 100 dollars", shouldEndSession));
} else if (data.Item === undefined) {
speechOutput = "I'm not sure what your base currency is, you can say, my base currency is US dollars";
callback(sessionAttributes,
buildSpeechletResponse("Currency Question", speechOutput, "my base currency is US dollars", shouldEndSession));
} else {
shouldEndSession = true;
basecurrency = data.Item.BaseCurrency
sessionAttributes = createBaseCurrencyAttributes(basecurrency);
if (getBaseCurrencyMapping(targetcurrency) == getBaseCurrencyMapping(basecurrency))
{
speechOutput = "The two currencies are the same. Please try again";
callback(sessionAttributes,
buildSpeechletResponse("Base Currency Question", speechOutput, speechOutput, shouldEndSession));
}
getConversion(basecurrency, targetcurrency, function(conversion){
//list all the names of state representative
console.log(conversion)
var targetCurrencyValue = conversion.rates[targetcurrency];
console.log(amount / targetCurrencyValue)
speechOutput = "It's about " + (amount / targetCurrencyValue).toFixed(2) + " " + getBaseCurrencyWords(basecurrency) + " for " + amount + " " + getBaseCurrencyWords(targetcurrency);
callback(sessionAttributes,
buildSpeechletResponse("Conversion", speechOutput, repromptText, shouldEndSession));
});
}
});
}
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
}
function getConversionRateFromSession(intent, session, callback) {
var basecurrency;
var targetcurrency;
var repromptText = null;
var sessionAttributes = {};
var shouldEndSession = false;
var speechOutput = "";
var repNames = "";
var totalReps = 0;
if (session.attributes) {
basecurrency = session.attributes.BaseCurrency;
}
if (intent.slots) {
var baseCurrencySlot = intent.slots.BaseCurrency;
if (baseCurrencySlot && baseCurrencySlot.value){
basecurrency = getBaseCurrencyMapping(baseCurrencySlot.value);
}
var targetCurrencySlot = intent.slots.TargetCurrency;
if (targetCurrencySlot && targetCurrencySlot.value){
targetcurrency = getBaseCurrencyMapping(targetCurrencySlot.value);
}
}
console.log('base currency :' + basecurrency)
console.log('target currency :' + targetcurrency)
if (targetcurrency == null)
{
speechOutput = "I'm not sure what the currency is, you can say, What is exchange rate for dollars";
callback(sessionAttributes,
buildSpeechletResponse("Currency Question", speechOutput, "you can say, What is exchange rate for dollars", shouldEndSession));
} else
if (basecurrency) {
//http://whoismyrepresentative.com/getall_mems.php?zip=75034
shouldEndSession = true;
getConversion(basecurrency, targetcurrency, function(conversion){
console.log(targetcurrency)
speechOutput = "It's about " + conversion.rates[targetcurrency] + " " + getBaseCurrencyConversion(targetcurrency) + " to a " + getBaseCurrencyConversion(basecurrency);
callback(sessionAttributes,
buildSpeechletResponse("Conversion Result", speechOutput, speechOutput, shouldEndSession));
});
} else {
console.log('getItem')
var dynamo = new AWS.DynamoDB.DocumentClient();
var params = {
TableName : dynamoTableName,
Key:{
UserId: session.user.userId
}
};
dynamo.get(params, function (err, data) {
console.log(err)
console.log(data)
if (err) {
speechOutput = "I'm not sure what your base currency is, you can say, my base currency is US dollars";
callback(sessionAttributes,
buildSpeechletResponse("Base Currency Question", speechOutput, "my base currency is US dollars", shouldEndSession));
} else if (data.Item === undefined) {
speechOutput = "I'm not sure what your base currency is, you can say, my base currency is US dollars";
callback(sessionAttributes,
buildSpeechletResponse("Base Currency Question", speechOutput, "my base currency is US dollars", shouldEndSession));
} else {
shouldEndSession = true;
basecurrency = data.Item.BaseCurrency
sessionAttributes = createBaseCurrencyAttributes(basecurrency);
if (getBaseCurrencyMapping(targetcurrency) == getBaseCurrencyMapping(basecurrency))
{
speechOutput = "The two currencies are the same. Please try again";
callback(sessionAttributes,
buildSpeechletResponse("Base Currency Question", speechOutput, speechOutput, shouldEndSession));
}
getConversion(basecurrency, targetcurrency, function(conversion){
var targetCurrencyValue = conversion.rates[targetcurrency];
speechOutput = "It's about " + conversion.rates[targetcurrency] + " " + getBaseCurrencyWords(targetcurrency) + " to a " + getBaseCurrencyConversion(basecurrency);
callback(sessionAttributes,
buildSpeechletResponse("Conversion", speechOutput, speechOutput, shouldEndSession));
});
}
});
}
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
}
function getConversion(basecurrency, targetcurrency, callback) {
return http.get({
host: 'api.fixer.io',
path: "/latest?base=" + basecurrency + "&symbols=" + targetcurrency
}, function(response) {
// Continuously update stream with data
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
var parsed = JSON.parse(body);
callback(parsed);
});
});
}
// --------------- Helpers that build all of the responses -----------------------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
card: {
type: "Simple",
title: title,
content: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
};
}
function getBaseCurrencyWords(basecurrency)
{
switch(basecurrency.toLowerCase()) {
case "aud":
return "australian dollars"
case "bgn":
return "bulgarian levs"
case "brl":
return "brazilian reals"
case "cad":
return "canadian dollars"
case "chf":
return "swiss francs"
case "cny":
return "chinese yuans"
case "czk":
return "czech republic korunas"
case "dkk":
return "danish krones"
case "eur":
return "euros"
case "gbp":
return "british pounds"
case "hkd":
return "hong kong dollars"
case "hrk":
return "croatian kunas"
case "huf":
return "hungarian forints"
case "idr":
return "indonesian rupiahs"
case "ils":
return "israeli new sheqels"
case "inr":
return "indian rupees"
case "jpy":
return "japanese yen"
case "krw":
return "south korean wons"
case "mxn":
return "mexican pesos"
case "myr":
return "malaysian ringgits"
case "nok":
return "norwegian krones"
case "nzd":
return "new zealand dollars"
case "php":
return "philippine pesos"
case "pln":
return "polish zloty"
case "ron":
return "romanian leus"
case "rub":
return "russian rubles"
case "sek":
return "swedish kronas"
case "sgd":
return "singapore dollars"
case "thb":
return "thai bahts"
case "try":
return "turkish liras"
case "usd":
return "dollars"
case "zar":
return "south african rands"
default:
return "dollars"
}
}
function getBaseCurrencyConversion(basecurrency)
{
switch(basecurrency.toLowerCase()) {
case "aud":
return "australian dollar"
case "bgn":
return "bulgarian lev"
case "brl":
return "brazilian real"
case "cad":
return "canadian dollar"
case "chf":
return "swiss franc"
case "cny":
return "chinese yuan"
case "czk":
return "czech republic koruna"
case "dkk":
return "danish krone"
case "eur":
return "euro"
case "gbp":
return "british pound"
case "hkd":
return "hong kong dollar"
case "hrk":
return "croatian kuna"
case "huf":
return "hungarian forint"
case "idr":
return "indonesian rupiah"
case "ils":
return "israeli new sheqel"
case "inr":
return "indian rupee"
case "jpy":
return "japanese yen"
case "krw":
return "south korean won"
case "mxn":
return "mexican peso"
case "myr":
return "malaysian ringgit"
case "nok":
return "norwegian krone"
case "nzd":
return "new zealand dollar"
case "php":
return "peso"
case "pln":
return "polish zloty"
case "ron":
return "romanian leus"
case "rub":
return "russian ruble"
case "sek":
return "swedish krona"
case "sgd":
return "singapore dollar"
case "thb":
return "thai baht"
case "try":
return "turkish lira"
case "usd":
return "dollar"
case "zar":
return "south african rand"
default:
return "dollar"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment