Sanjeev Kumar
Published © GPL3+

Flight Search

Find the cheapest flights with Alexa.

BeginnerShowcase (no instructions)2 hours838
Flight Search

Things used in this project

Hardware components

Echo Dot
Amazon Alexa Echo Dot
×1
Amazon Echo
Amazon Alexa Amazon Echo
×1

Software apps and online services

Google qpx express api
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit

Story

Read more

Code

Alexa Intents

Plain text
  "INTENTS" 
{
  "intents":[
    {
      "intent":"TravelDate",
      "slots":[{
        "name":"date",
        "type":"AMAZON.DATE"
      }]
    },
   	{ 
     "intent":"CityCodes",
     "slots":[{
     "name":"city_codes",
     "type":"CITY_CODE"
     }]
   },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
     {
      "intent": "AMAZON.CancelIntent"
    }
]
}

"UTTERANCES"
CityCodes {city_codes}

TravelDate on {date}
TravelDate {date}

AMAZON.HelpIntent can you help me
AMAZON.HelpIntent help 
AMAZON.HelpIntent help me
AMAZON.HelpIntent how can you help me
AMAZON.HelpIntent i need help
AMAZON.HelpIntent i need assitance
AMAZON.HelpIntent i am stuck

AMAZON.StopIntent stop
AMAZON.StopIntent off 
AMAZON.StopIntent exit
AMAZON.StopIntent cancel
AMAZON.StopIntent bye
AMAZON.StopIntent shut up
AMAZON.StopIntent end
AMAZON.StopIntent never mind
AMAZON.StopIntent forget it
AMAZON.StopIntent quit
AMAZON.StopIntent shut down
AMAZON.StopIntent no thanks
AMAZON.StopIntent no thanks

AMAZON.CancelIntent stop
AMAZON.CancelIntent off
AMAZON.CancelIntent exit
AMAZON.CancelIntent cancel
AMAZON.CancelIntent bye
AMAZON.CancelIntent shut up
AMAZON.CancelIntent end
AMAZON.CancelIntent never mind
AMAZON.CancelIntent forget it
AMAZON.CancelIntent no thanks

"SLOTS" --> CITY_CODE
aac
aae
aal
aan
aar
aat
abd
abe
abi
abj
abm
abq
abr
abs
abv
abx
aby
abz
aca
ace
ach
aci
ack
act
acv
acy
ada
adb
add
ade
adf
adj
adl
ady
adz
aeh
aep
aer
aes
aga
agb
agp
agr
ags
agu
agz
ahb
ahn
aho
ahu
aja
ajf
ajn
aju
ajy
akl
akn
akt
ala
alb
alc
alf
alg
alh
alj
alo
alp
alv
alw
aly
ama
amd
amm
ams
anb
anc
ank
anr
anu
aoi
aoj
aok
aoo
apf
apw
aqj
arb
arh
ark
arn
asb
ase
asj
ask
asm
asp
asr
asu
asw
ath
atl
ato
atq
atw
aty
atz
aua
aue
aug
auh
aur
aus
avl
avp
axa
axs
axt
ayq
ayr
ayt
ayu
ayw
azb
azo
azp
azs
bah
bak
baq
bbi
bbt
bby
bcn
bco
bda
bdb
bdl
bdo
bdq
bdr
bds
bdu
beb
beg
beh
bek
bel
ben
beo
ber
bes
bet
bew
bey
bfd
bfl
bfn
bfo
bfs
bga
bgf
bgi
bgm
bgo
bgr
bgu
bgw
bgy
bhc
bhd
bhe
bhj
bhm
bho
bhq
bhu
bhv
bhx
bia
bil
bio
biq
bis
biv
bji
bjl
bjm
bjv
bjx
bjz
bki
bkk
bkl
bko
bkw
bkx
bla
blf
bli
blk
bll
blq
blr
blt
blz
bma
bme
bmg
bmi
bmp
bna
bne
bnk
bnn
bnp
bob
bod
bog
boh
boi
boj
bom
bon
boo
bos
boy
bpt
bqk
bqn
brc
brd
bre
bri
brl
brn
brr
brs
bru
bsb
bsl
bsr
btm
btr
bts
btu
btv
bud
bue
buf
bug
buh
buq
bur
bvb
bwi
bwn
bwt
bxo
bxs
byk
byu
bze
bzl
bzn
bzv
cab
cae
cag
cai
cak
cal
can
cas
cay
cbb
cbg
cbr
cbu
ccj
ccr
ccs
ccu
ccz
cdc
cdg
cdv
ceb
cec
ced
cen
ces
cfe
cfg
cfn
cfs
cfu
cga
cgb
cgh
cgk
cgn
cgp
cgq
cgr
cgu
cha
chc
chg
chi
cho
chq
chs
cia
cic
cid
cip
ciw
cjb
cjc
cjl
cjs
ckb
ckg
cky
cld
cle
cll
clm
clo
clq
clt
cly
cmb
cme
cmf
cmh
cmi
cmn
cmq
cmx
cnd
cnf
cns
cnx
cod
cok
con
coo
cor
cos
cpd
cph
cpr
cpt
cre
crf
crg
crp
crw
csg
csi
csn
cst
cta
ctg
ctn
cts
ctu
cul
cun
cur
cuu
cvg
cvm
cvq
cvt
cwa
cwb
cwl
cxi
cxt
cys
cyu
cza
czl
czm
dab
dac
dal
dam
dan
dar
day
dbo
dbq
dbv
dby
ddi
dec
ded
del
den
det
dfw
dha
dhn
dib
dil
diu
djb
dje
djj
djo
dki
dkr
dla
dlc
dlg
dlh
dlm
dlp
dme
dmk
dmm
dmu
dnd
dnr
dnz
dod
doh
dom
dpo
dps
drb
dro
drs
drw
dsa
dsk
dsm
dtm
dtt
dtw
dub
dud
duj
dur
dus
dut
dvl
dxb
dya
dyu
dza
eap
eas
eat
eau
eba
ebb
ebj
ebu
edi
edr
egc
ege
egs
ein
eis
eki
eko
elh
ell
elm
elp
els
ely
ema
emd
emy
ena
enc
enf
epr
erc
erf
eri
erz
esb
esc
esf
eth
etz
eug
eve
evn
evv
ewn
ewr
ext
eyw
eze
fae
fai
fao
far
fat
fay
fbm
fbu
fca
fco
fdf
fdh
fez
fhu
fie
fih
fjr
fkb
fki
fkl
fks
flg
fll
fln
flo
flr
fmn
fmo
fmy
fna
fnc
fni
fnj
fnt
fod
for
fou
fpo
fra
fri
frj
fro
fru
frw
fsc
fsd
fsm
fsp
fue
fuk
fut
fwa
fyv
gad
gaj
gau
gbe
gcc
gci
gcm
gcn
gdl
gdn
gdv
geg
geo
get
gex
gff
gfk
ggg
ggw
ghb
gib
gig
gil
gjl
gjt
gkl
gla
glh
glt
gnb
gnd
gne
gnv
goa
goi
gon
goo
got
gou
gov
goz
gpa
gpt
gpz
grb
grj
gro
grq
grr
gru
grx
grz
gsi
gso
gsp
gte
gtf
gti
gtn
gua
guc
gum
gva
gwd
gwe
gwl
gwt
gwy
gye
gyn
gyp
gza
gzt
hac
hag
hah
haj
ham
han
hap
har
hau
hav
hba
hbh
hbx
hdd
hdn
hdy
hel
her
hew
hfa
hft
hgh
hgo
hhh
hhn
hib
hii
hij
hir
his
hjr
hkd
hkg
hks
hkt
hky
hla
hlh
hln
hlp
hlt
hlz
hmh
hmo
hna
hnd
hnh
hnk
hnl
hns
hog
hom
hon
hoq
hor
hou
hpn
hrb
hre
hrg
hrk
hrl
hsv
hta
hti
hts
huf
huh
hui
hux
huy
hvb
hvn
hvr
hwn
hya
hyd
hyg
iad
iag
iah
ibz
icn
ict
ida
idr
iev
ifl
igh
igr
ijx
ikt
ile
ili
ilm
ilp
ily
imf
ind
ini
inl
inn
inv
iom
iou
ipc
ipl
ipt
iqt
irg
iro
isa
isb
isg
isk
isl
iso
isp
ist
ith
itm
ito
ivc
ivl
ixa
ixb
ixc
ixd
ixe
ixg
ixj
ixl
ixm
ixr
ixs
ixu
ixw
ixz
iyk
izm
jaa
jac
jad
jaf
jag
jai
jak
jal
jam
jan
jaq
jau
jax
jbr
jcb
jck
jcm
jdf
jdh
jdz
jed
jee
jef
jer
jga
jgb
jgn
jgs
jhb
jhe
jhg
jhm
jhq
jhw
jib
jij
jil
jim
jin
jip
jir
jiu
jiw
jji
jjn
jkg
jkh
jkr
jkt
jkv
jln
jlr
jls
jmb
jmk
jmo
jms
jmu
jna
jnb
jng
jni
jnu
jnx
jnz
joe
joi
jol
jon
jos
jpa
jqe
jrh
jro
jrs
jsa
jsi
jsm
jsr
jst
jti
jub
jui
juj
jul
jum
jun
jut
juv
jvl
jwa
jxn
jyv
kaj
kan
kao
kbl
kbp
kby
kcc
kce
kch
kcm
kcz
kdd
kdu
kef
kel
kem
kgc
kgi
kgl
kgs
khh
khi
khj
khv
kid
kij
kik
kim
kin
kir
kiv
kiw
kix
kkn
klr
klu
klw
klx
klz
kmi
kmj
kmp
kno
kns
knu
knx
koa
koi
koj
kok
krb
krk
krn
krp
krs
krt
ksd
ksl
ksu
kta
ktb
ktm
ktn
ktr
ktt
kua
kuh
kul
kuo
kva
...

This file has been truncated, please download it to see its full contents.

Flight Search lambda function

JavaScript
it is a node.js code written in lambda function using amazon web services
'use strict';
var https = require("https");
/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
 * The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as
 * testing instructions are located at http://amzn.to/1LzFrj6
 *
 * For additional samples, visit the Alexa Skills Kit Getting Started guide at
 * http://amzn.to/1LGWsLG
 */


// --------------- 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,
    };
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: '1.0',
        sessionAttributes,
        response: speechletResponse,
    };
}
/**
 * called when session ended
*/
function handleSessionEndRequest(callback) {
    const cardTitle = 'Session Ended';
    const speechOutput = 'Thank you for using cheap flight search. Have a nice day!';
    // Setting this to true ends the session and exits the skill.
    const shouldEndSession = true;
    callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}
/**
 * function to get city codes .
*/

function  getCityCodes(intent, session, callback){
    var sessionAttributes = {};
    let speechOutput="";
    let repromptText="";
    const cardTitle = intent.name;
    const shouldEndSession = false;
    console.log(session.attributes.originCityCode);
    if(session.attributes.originCityCode!==undefined){
        sessionAttributes={"originCityCode":session.attributes.originCityCode,"destinationCityCode":intent.slots.city_codes.value}; 
        speechOutput = 'on which date you want to travel';
        repromptText = "please tell me the travel date";
    }
    else{
        sessionAttributes={"originCityCode":intent.slots.city_codes.value};
        speechOutput = 'tell me destination city code';
        repromptText = "tell me destination city code";
    }
    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

/**
 * getting flight details by providing parameter like source, destination and departure date.
*/
function searchFlight(intent, session, callback) {
    const cardTitle = intent.name;
    const source =session.attributes.originCityCode;
    const dest = session.attributes.destinationCityCode;
    console.log(source+" "+dest);
    const travelDate = intent.slots.date.value;
    console.log(travelDate);
    let repromptText = '';
    let sessionAttributes = {};
    const shouldEndSession = false;
    let speechOutput = '';
    var body="";
    var endpoint="https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyApFEhzPRXirKSY1ST5IMxP-_HjiBKiypY";
    var jsonObject = JSON.stringify({
			"request": {
				"slice": [
				          {
				        	  "origin": source,
				        	  "destination": dest,
				        	  "date": travelDate
				          }
				          ],
				 "passengers": {
				        	  "adultCount": 1,
				        	  "infantInLapCount": 0,
				        	  "infantInSeatCount": 0,
				        	  "childCount": 0,
				        	  "seniorCount": 0
				          },
				 "solutions": 1,
				 "refundable": false
			}
	});
     var optionspost = {
     host : 'www.googleapis.com',
     path : '/qpxExpress/v1/trips/search?key=AIzaSyApFEhzPRXirKSY1ST5IMxP-_HjiBKiypY',
     method : 'POST',
     headers: {
            'Content-Type': 'application/json',
        },
    };
     var reqPost = https.request(optionspost, function(res) {
        res.on('data', function (chunk) {
            body += chunk;
        });
     res.on('end', function() {
      var data = JSON.parse(body);
      console.log(data);
      var data1=data.trips.tripOption[0];
      var from=data.trips.data.city[0].name;
      var to=data.trips.data.city[1].name;
	  var slice=data1.slice[0];
	  var segment=slice.segment[0];
	  var carrier=segment.flight.carrier;
	  var number=segment.flight.number;
	  var leg=segment.leg[0];
	  var depart=leg.departureTime;
	  var arrival=leg.arrivalTime;
	  var departArray=depart.split("T");
	  var departDate=departArray[0];
	  var departTimeArray=departArray[1].split("+");
	  var departTime=departTimeArray[0];
	  var arrivalArray=arrival.split("T");
	  var arrivalDate=arrivalArray[0];
	  var arrivalTimeArray=arrivalArray[1].split("+");
	  var arrivalTime=arrivalTimeArray[0];
	  var flightNumber=""+carrier+number;
      speechOutput="hi, your flight number, "+flightNumber+", will depart from, "+from+", on, "+departDate+", at "+departTime+", and, it will arrive, "+to+", on, "+arrivalDate+", at, "+arrivalTime+", .The total fare of your trip will be, "+data1.saleTotal+", anything else that i can help you with.";
      repromptText=speechOutput;
      callback(sessionAttributes,
         buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
         
     });
    });

    reqPost.write(jsonObject);
    reqPost.end();
    reqPost.on('error', (e) => {
    console.error(e);
});
}

/**
 * Welcome message when skill launched 
*/
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 = 'Hi, welcome to flight search, please tell me origin city code';
    // 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 = "tell me origin city code";
    const shouldEndSession = false;
    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
/**
 * 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 === 'CityCodes') {
        getCityCodes(intent, session, callback);
    }else if (intentName === 'TravelDate') {
        searchFlight(intent, session, callback);
    }
    else if (intentName === 'AMAZON.HelpIntent') {
        getWelcomeResponse(callback);
    } else if (intentName === 'AMAZON.StopIntent' || intentName === 'AMAZON.CancelIntent') {
        handleSessionEndRequest(callback);
    } else {
        throw new Error('Invalid intent');
    }
}


/**
 * Called when the session starts.
 */
function onSessionStarted(sessionStartedRequest, session) {
    console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}
/**
 * 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
}

exports.handler = (event, context, callback) => {
    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.ask.skill.1f2e8dab-fe0f-474d-a775-e2750791ebb0') {
             callback('Invalid Application ID');
        }
        if (event.session.new) {
            onSessionStarted({ requestId: event.request.requestId }, event.session);
        }
          if (event.request.type === 'LaunchRequest') {
            onLaunch(event.request,
                event.session,
                (sessionAttributes, speechletResponse) => {
                    callback(null, buildResponse(sessionAttributes, speechletResponse));
                });
        } else 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);
            callback();
        }
    } catch (err) {
        callback(err);
    }
};
   


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

Credits

Sanjeev Kumar

Sanjeev Kumar

1 project • 0 followers
honest and self motivated.

Comments