Geetha
Published © GPL3+

Alexa Spice: Google Translate

A useful Alexa Skill which uses Google Translate API to translate a list of spices from around the World into different languages.

IntermediateProtip5 hours2,804

Things used in this project

Hardware components

Amazon Echo
Amazon Alexa Amazon Echo
×1

Software apps and online services

AWS Lambda
Amazon Web Services AWS Lambda
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit
Google Translate API
Node.js

Story

Read more

Schematics

Algorithm

VUI

Code

index.js

JavaScript
Insert your Rappid project name, Rappid Api and Google Api
'use strict';
const RapidAPI = require('rapidapi-connect');
const rapid = new RapidAPI('Spice1', 'Rapid Api Key');//Insert your Rapid API Key




// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: 'PlainText',
            text: output,
        },
        card: {
            type: 'Simple',
            title: `SessionSpeechlet - ${title}`,
            content: `SessionSpeechlet - ${output}`,
        },
        reprompt: {
            outputSpeech: {
                type: 'PlainText',
                text: repromptText,
            },
        },
        shouldEndSession:shouldEndSession
    };
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: '1.0',
        sessionAttributes,
        response: speechletResponse,
    };
}


// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    const sessionAttributes = {};
    const cardTitle = 'Welcome';
    const speechOutput = 'Welcome to the Spice Translate skill. Say something like translate Basil to German';
    // 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.
    const repromptText = 'Say something like translate basil to German';
    const shouldEndSession = false;

    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
function getHelpResponse(intent, session, callback) {
    // declare session attributes
    var sessionAttributes = {};
    // define title for the card.
    var cardTitle = "Spice Translate Help";
    // here is the help provided to the user
    var speechOutput = "Ask Spice Translate to translate any spice word to specified language in skill info";

    // if user does not respond, this will be played after a few seconds
    var repromptText = "Are you there";

    // make sure that the session is not ended
    var shouldEndSession = false;

    // build the speech that user will hear
    callback({},
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

function getExitResponse(intent, session, callback) {
    // declare session attributes
    var sessionAttributes = {};
    // define title for the card.
    var cardTitle = "Spice Translate Exit";
    // here is the help provided to the user
    var speechOutput = "Thanks For trying This Skill.Have a Nice Day!";

    // if user does not respond, this will be played after a few seconds
 

    // make sure that the session is not ended
    var shouldEndSession = true;

    // build the speech that user will hear
    callback({},
        buildSpeechletResponse(cardTitle, speechOutput,null, shouldEndSession));
}

/**
 * Intent handlers
 */
 
function translate(intent, session, callback) {
    const GoogleAPIKey = 'Google Translate API KEY';//Insert your Google API Key


//More Languages can be added by specifying their ISO Standard Langugae code like 'en' etc....
    const langCodes = {
        "German" : "de",
        "Dutch" : "nl",
        "English" : "en",
        "French" : "fr",
        "Italian" : "it",
        "Polish" : "pl",
        "Russian" : "ru",
        "Spanish" : "es"
    };
    const source = intent.slots.Source.value;
    const lang = intent.slots.Language.value;
    const langCode = langCodes[lang];

    //Call RapidAPI
    rapid.call('GoogleTranslate', 'translateAutomatic', {
        string : source,
        apiKey: GoogleAPIKey,
        targetLanguage: langCode
    })
        .on('error', (payload) => {
            callback({},
                buildSpeechletResponse('Spice Translate', `Sorry, translation not available`, null, false));
        })
        .on ('success', (payload) => {
            callback({},
                buildSpeechletResponse('Spice Translate', `${source} in ${lang} is ${payload}`, null, false));
        });

    //callback({}, buildSpeechletResponse('Translate Demo', `Translating ${source} to ${lang}`, null, false));
}


// --------------- Events -----------------------


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(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}`);

    const intent = intentRequest.intent;
    const intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    if (intentName === 'Translate') {
        translate(intent, session, callback);
    } else if ("AMAZON.HelpIntent" === intentName) {
        getHelpResponse(intent, session, callback);
    }else if ("AMAZON.StopIntent" === intentName) {
        getExitResponse(intent, session, callback);
    }

    else {
        throw new Error('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}`);
    
}


// --------------- Main handler -----------------------

// 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,callback) {
    try {
        console.log("event.session.application.applicationId=" + event.session.application.applicationId);

        // if it is a new session, do initialization
        if (event.session.new) {
            onSessionStarted({requestId: event.request.requestId}, event.session);
        }

        // detemine the type of request and call apporpriate function
        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,
                event.session,
                function callback(sessionAttributes, speechletResponse) {
                    context.succeed(buildResponse(sessionAttributes, speechletResponse));
                });
        } if (event.request.type === 'IntentRequest') {
            onIntent(event.request,
                event.session,
                (sessionAttributes, speechletResponse) => {
                    callback(null,buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request, event.session);
            context.succeed();
        }
    } catch (e) {
        context.fail("Exception: " + e);
    }
};

Intent Schema}

JSON
Copy and Paste the Intent Schema given below in Amazon Skill Development Page
{ 
   "intents": [ 
       { 
           "intent" : "Translate", 
           "slots": [ 
               { 
                   "name" : "Source", 
                   "type" : "SOURCE" 
               }, 
               { 
                   "name" : "Language", 
                   "type" : "LANGUAGES_LIST" 
               } 
           ] 
       }, 
     { 
     "intent": "AMAZON.HelpIntent" 
   }, 
     { 
     "intent":"AMAZON.StopIntent" 
     } 
   ] 
}

Sample Utternces

Textile
Translate translate {Source} to {Language} 
Translate how to say {Source} in {Language} 
Translate to translate {Source} to {Language} 
Translate get translation for {Source} in {Language} 
Translate what is {Source} in {Language} 
AMAZON.HelpIntent help 
AMAZON.HelpIntent Help 
AMAZON.StopIntent Stop 
AMAZON.StopIntent cancel 
AMAZON.StopIntent Cancel 

Credits

Geetha

Geetha

1 project • 1 follower
Intrested in doing IOT projects

Comments