Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
vincent wong
Published © GPL3+

Alexa, ask Albert Einstein Facts

Albert Einstein Facts is a skill that tells a fact about Albert Einstein.

BeginnerFull instructions provided924
Alexa, ask Albert Einstein Facts

Things used in this project

Story

Read more

Code

Intent Schema

snippets
{
  "intents": [
    {
      "intent": "GetNewFactIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
 }

Utterances

snippets
GetNewFactIntent a fact
GetNewFactIntent a albert einstein fact
GetNewFactIntent tell me a fact
GetNewFactIntent tell me a albert einstein fact
GetNewFactIntent give me a fact
GetNewFactIntent give me a albert einstein fact
GetNewFactIntent tell me a trivia
GetNewFactIntent tell me a albert einstein trivia
GetNewFactIntent give me a trivia
GetNewFactIntent give me a albert einstein trivia
GetNewFactIntent give me some information
GetNewFactIntent give me some albert einstein information
GetNewFactIntent tell me something
GetNewFactIntent give me something

AlexaSkill.js

JavaScript
/**
    Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at

        http://aws.amazon.com/apache2.0/

    or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

'use strict';

function AlexaSkill(appId) {
    this._appId = appId;
}

AlexaSkill.speechOutputType = {
    PLAIN_TEXT: 'PlainText',
    SSML: 'SSML'
}

AlexaSkill.prototype.requestHandlers = {
    LaunchRequest: function (event, context, response) {
        this.eventHandlers.onLaunch.call(this, event.request, event.session, response);
    },

    IntentRequest: function (event, context, response) {
        this.eventHandlers.onIntent.call(this, event.request, event.session, response);
    },

    SessionEndedRequest: function (event, context) {
        this.eventHandlers.onSessionEnded(event.request, event.session);
        context.succeed();
    }
};

/**
 * Override any of the eventHandlers as needed
 */
AlexaSkill.prototype.eventHandlers = {
    /**
     * Called when the session starts.
     * Subclasses could have overriden this function to open any necessary resources.
     */
    onSessionStarted: function (sessionStartedRequest, session) {
    },

    /**
     * Called when the user invokes the skill without specifying what they want.
     * The subclass must override this function and provide feedback to the user.
     */
    onLaunch: function (launchRequest, session, response) {
        throw "onLaunch should be overriden by subclass";
    },

    /**
     * Called when the user specifies an intent.
     */
    onIntent: function (intentRequest, session, response) {
        var intent = intentRequest.intent,
            intentName = intentRequest.intent.name,
            intentHandler = this.intentHandlers[intentName];
        if (intentHandler) {
            console.log('dispatch intent = ' + intentName);
            intentHandler.call(this, intent, session, response);
        } else {
            throw 'Unsupported intent = ' + intentName;
        }
    },

    /**
     * Called when the user ends the session.
     * Subclasses could have overriden this function to close any open resources.
     */
    onSessionEnded: function (sessionEndedRequest, session) {
    }
};

/**
 * Subclasses should override the intentHandlers with the functions to handle specific intents.
 */
AlexaSkill.prototype.intentHandlers = {};

AlexaSkill.prototype.execute = function (event, context) {
    try {
        console.log("session applicationId: " + event.session.application.applicationId);

        // Validate that this request originated from authorized source.
        if (this._appId && event.session.application.applicationId !== this._appId) {
            console.log("The applicationIds don't match : " + event.session.application.applicationId + " and "
                + this._appId);
            throw "Invalid applicationId";
        }

        if (!event.session.attributes) {
            event.session.attributes = {};
        }

        if (event.session.new) {
            this.eventHandlers.onSessionStarted(event.request, event.session);
        }

        // Route the request to the proper handler which may have been overriden.
        var requestHandler = this.requestHandlers[event.request.type];
        requestHandler.call(this, event, context, new Response(context, event.session));
    } catch (e) {
        console.log("Unexpected exception " + e);
        context.fail(e);
    }
};

var Response = function (context, session) {
    this._context = context;
    this._session = session;
};

function createSpeechObject(optionsParam) {
    if (optionsParam && optionsParam.type === 'SSML') {
        return {
            type: optionsParam.type,
            ssml: optionsParam.speech
        };
    } else {
        return {
            type: optionsParam.type || 'PlainText',
            text: optionsParam.speech || optionsParam
        }
    }
}

Response.prototype = (function () {
    var buildSpeechletResponse = function (options) {
        var alexaResponse = {
            outputSpeech: createSpeechObject(options.output),
            shouldEndSession: options.shouldEndSession
        };
        if (options.reprompt) {
            alexaResponse.reprompt = {
                outputSpeech: createSpeechObject(options.reprompt)
            };
        }
        if (options.cardTitle && options.cardContent) {
            alexaResponse.card = {
                type: "Simple",
                title: options.cardTitle,
                content: options.cardContent
            };
        }
        var returnResult = {
                version: '1.0',
                response: alexaResponse
        };
        if (options.session && options.session.attributes) {
            returnResult.sessionAttributes = options.session.attributes;
        }
        return returnResult;
    };

    return {
        tell: function (speechOutput) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                shouldEndSession: true
            }));
        },
        tellWithCard: function (speechOutput, cardTitle, cardContent) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                cardTitle: cardTitle,
                cardContent: cardContent,
                shouldEndSession: true
            }));
        },
        ask: function (speechOutput, repromptSpeech) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                reprompt: repromptSpeech,
                shouldEndSession: false
            }));
        },
        askWithCard: function (speechOutput, repromptSpeech, cardTitle, cardContent) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                reprompt: repromptSpeech,
                cardTitle: cardTitle,
                cardContent: cardContent,
                shouldEndSession: false
            }));
        }
    };
})();

module.exports = AlexaSkill;

index.js

JavaScript
/**
 * App ID for the skill
 */
var APP_ID = "amzn1.echo-sdk-ams.app.40775819-ac5b-41af-901c-f287258942ff";   // undefined; //replace with "amzn1.echo-sdk-ams.app.[your-unique-value-here]";

/**
 * Array containing Albert Einstein facts.
 */
var EINSTEIN_FACTS = [
	"Albert Einstein was born on March 14, 1879 in Ulm, the Kingdom of Württemberg (a state that existed in Germany from 1805 to 1918).",
	"Albert Einstein was a famous German-born scientist and theoretical physicist who is credited for the development of the general theory of relativity.",
	"His parents were Jewish, they were called Hermann Einstein and Pauline Koch. His father was an engineer and salesman, and his mother was a housewife. He had a younger sister called Maja. ",
	"He began his education when he was five years old at a Catholic elementary school. He studied at the school for three years before moving to the Luitpold Gymnasium in Munich. The Luitpold Gymnasium has since been renamed the 'Albert Einstein Gymnasium'. Here, he received his primary and secondary school education.",
	"Albert Einstein was a curious and inquisitive child with a talent for music. He enjoyed playing the violin and would continue to do so throughout his adult life. He often felt like a loner, even as an adult, and for this reason, he didn't enjoy his school days very much.",
	"His family moved to Italy during the 1890s, Albert Einstein remained in Munich in order to complete his schooling. He joined his family in Italy when he was faced with military duty. He used a note from his doctor, claiming he was suffering from nervous exhaustion, to excuse himself from his studies.",
	"Albert Einstein was accepted into the Swiss Federal Polytechnic School in Zurich as a result of his entrance exam score which was outstanding for both physics and mathematics.",
	"Whilst studying at the Polytechnic school in Zurich, he met a girl called Mileva Maric who became his future wife. Albert Einstein's parents did not approve of their relationship as Mileva was of a different nationality to their son's. This didn't stop the couple from seeing one another. They had a daughter together in 1902, she was called Lieserl. The couple didn't raise the child, she may have been adopted.",
	"Albert Einstein married Mileva Maric in 1903, following the death of his father. They had two sons together, their names were Hans and Eduard. The couple were married for approximately 16 years, they divorced in 1919. During his marriage to Mileva Maric, Albert Einstein had a secret love affair with a woman called Elsa Löwenthal. Albert Einstein married her in 1919 following his divorce to Mileva Maric. His second marriage lasted for approximately 17 years during which time he continued to have affairs with other women. His wife, Elsa Löwenthal, died in 1936.",
	"He worked for a Swiss patent office from 1902 as a clerk. It was during this time that his theories really started to develop. He produced four papers which were published in 1905 in a physics journal called the Annalen der Physik. Albert Einstein created the equation E=mc2 which was published in his fourth paper. 1905 became known as a 'miracle year' for Albert Einstein.",
	"From 1913 to 1933, Albert Einstein was the director of the Kaiser Wilhelm Institute for Physics. In 1915, he finished the general theory of relativity. This was one of the most important points of his life as he was finally able to explain a theory which he'd worked on for such a long time",
	"He won the Nobel Prize for Physics in 1921. He wasn't presented with the award straight away as some doubted his ideas on relativity.",
	"In 1933, Hitler came into power over Germany and Albert Einstein, being Jewish, became a target to the Nazis. He feared for his life, and his works which were at risk of becoming detriment to Nazi book burnings, and as a consequence, he moved to the United States to escape. In 1940, he became an American citizen.",
	"Albert Einstein wrote to the President of the United States, Franklin D. Roosevelt, on the day prior to the outbreak of the Second World War. He wanted to alert the President to the atomic bomb research being carried out by the Nazis. In his letter, he advised that the United States should concentrate on its own nuclear weapons research.",
	"Following his letter to President Franklin D. Roosevelt, the Manhattan Project was initiated. The race had begun and the United States focused their efforts on producing the first nuclear weapons. The U.S. became the first country to create an atomic bomb during WWII.",
	"Albert Einstein was a pacifist, he didn't believe in war. He felt regretful later in life for having written to President Franklin D. Roosevelt advising that the United States engage in the development of the atomic bomb. The following quote by Albert Einstein reflects upon the situation, 'I made one great mistake in my life - when I signed the letter to President Roosevelt recommending that atom bombs be made; but there was some justification - the danger that the Germans would make them ...'",
	"He was an avid supporter and campaigner of civil rights. Albert Einstein believed that the United States was plagued with racism and he wanted to see equal rights given to black people. During a speech at Lincoln University, he told the students that 'he didn't intend to be quiet about it.'",
	"Albert Einstein was good friends with the famous movie star Charlie Chaplin. Albert Einstein's wife, Elsa, told Charlie Chaplin about the moment when Albert completed the general theory of relativity. She recalled that he'd seemed lost in thought at breakfast time, ignoring his food and instead, playing the piano and writing notes. He then took to his study where he remained for two weeks. When he reappeared, he held two sheets of paper containing his completed theory of relativity.",
	"During his lifetime, Albert Einstein carefully observed, researched and investigated many matters including force, superconductivity, gravitational waves, wormholes, energy, cosmology, the quantum theory and quantum mechanics which he later felt disappointed with, although he'd helped to create it, he felt that it had been left unfinished. He published over 300 scientific papers during his lifetime.",
	"Albert Einstein died in Princeton Hospital, New Jersey on April 17, 1955 at the age of 76, following a rupture to an abdominal aortic aneurysm which resulted in internal bleeding. He refused surgery as he didn't believe in prolonging life artificially and he wanted his own to end elegantly. As per his wishes, Albert Einstein was cremated and the location of his ashes remains unknown.",
];

/**
 * The AlexaSkill prototype and helper functions
 */
var AlexaSkill = require('./AlexaSkill');

/**
 * EinsteinFacts is a child of AlexaSkill.
 * To read more about inheritance in JavaScript, see the link below.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance
 */
var EinsteinFacts = function () {
    AlexaSkill.call(this, APP_ID);
};

// Extend AlexaSkill
EinsteinFacts.prototype = Object.create(AlexaSkill.prototype);
EinsteinFacts.prototype.constructor = EinsteinFacts;

EinsteinFacts.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {
    console.log("EinsteinFacts onSessionStarted requestId: " + sessionStartedRequest.requestId
        + ", sessionId: " + session.sessionId);
    // any initialization logic goes here
};

EinsteinFacts.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
    console.log("EinsteinFacts onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    handleNewFactRequest(response);
};

/**
 * Overridden to show that a subclass can override this function to teardown session state.
 */
EinsteinFacts.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {
    console.log("EinsteinFacts onSessionEnded requestId: " + sessionEndedRequest.requestId
        + ", sessionId: " + session.sessionId);
    // any cleanup logic goes here
};

EinsteinFacts.prototype.intentHandlers = {
    "GetNewFactIntent": function (intent, session, response) {
        handleNewFactRequest(response);
    },

    "AMAZON.HelpIntent": function (intent, session, response) {
        response.ask("You can ask Albert Einstein Facts tell me a Albert Einstein fact, or, you can say exit... What can I help you with?", "What can I help you with?");
    },

    "AMAZON.StopIntent": function (intent, session, response) {
        var speechOutput = "Thank you for using Albert Einstein Facts.  Goodbye";
        response.tell(speechOutput);
    },

    "AMAZON.CancelIntent": function (intent, session, response) {
        var speechOutput = "Thank you for using Albert Einstein Facts.  Goodbye";
        response.tell(speechOutput);
    }
};

/**
 * Gets a random new fact from the list and returns to the user.
 */
function handleNewFactRequest(response) {
    // Get a random Albert Einstein fact from the Albert Einstein facts list
    var factIndex = Math.floor(Math.random() * EINSTEIN_FACTS.length);
    var fact = EINSTEIN_FACTS[factIndex];

    // Create speech output
    var speechOutput = "Here's your Albert Einstein fact: " + fact;

    response.tellWithCard(speechOutput, "EinsteinFacts", speechOutput);
}

// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
    // Create an instance of the EinsteinFacts skill.
    var einsteinFacts = new EinsteinFacts();
    einsteinFacts.execute(event, context);
};

Credits

vincent wong

vincent wong

81 projects • 205 followers

Comments