Skip to content

Instantly share code, notes, and snippets.

@Sisekelo
Created September 18, 2019 13:03
Show Gist options
  • Select an option

  • Save Sisekelo/9b0f51cc3ac8632d35d5dfcd089eb6ee to your computer and use it in GitHub Desktop.

Select an option

Save Sisekelo/9b0f51cc3ac8632d35d5dfcd089eb6ee to your computer and use it in GitHub Desktop.
'use strict';
// Your Google Cloud Platform project ID
const projectId = 'quickstart-1550429036021';
const functions = require('firebase-functions');
const {
WebhookClient
} = require('dialogflow-fulfillment');
const {
Card,
Suggestion
} = require('dialogflow-fulfillment');
const https = require('https');
const request = require('request');
/*const BitlyClient = require('bitly');
const bitly = new BitlyClient('71070a76e59d7140e1b2eca2f1ed851ee97d2d5f');*/
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
let action = request.body.queryResult.action;
var intent = request.body.queryResult.intent.displayName;
const parameters = request.body.queryResult.parameters;
const quizParameters = request.body.queryResult.outputContexts;
//send info
var joe = request.body.session;
var slash = joe.lastIndexOf('/');
var p = '';
slash += 1
for (var i = slash; i <= joe.length - 1; i++) {
p += joe[i];
}
//p is the cellphone number
p = p.replace(/_/g, '');
var timestamp = new Date();
var keeper = 0;
var finalResponse = "";
/*https.get('https://api.airtable.com/v0/appRAe4mxfGI1VDl6/users?api_key=keynre40bTqHjQ7AD', (resp) => {
var data;
var name;
var length;
resp.on('data', (chunk) => {
data = JSON.parse(chunk);
length = data.records.length;
console.log("Users length: " + length);
//find description
for (var k = 0; k < length; k++) {
if (data.records[k].fields.Number == p) {
keeper++;
}
}
if(keeper == 0 ){
finalResponse += "Welcome to Msizi. I see this is your first time with us.🎉🎉🎉\n\n";
finalResponse += "Thank you for using Msizi. Our mission is to share learning materials with students.\n";
finalResponse += "\nHOW TO:\n*To use me ensure you choose one of the options given\n";
finalResponse += "*Past papers are updated as per your request\n\n";
finalResponse += "*To continue using Msizi, please make sure the number is saved*\n \n";
finalResponse += "👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿\n\n Send 'Hi' to start!"
// The whole response has been received. Print out the result.
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});*/
var Airtable = require('airtable');
var base = new Airtable({
apiKey: 'keynre40bTqHjQ7AD'
}).base('appRAe4mxfGI1VDl6');
base('users').create({
'Intent' : intent,
'Number': p,
'Timestamp':timestamp
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(record.getId());
});
//end of sending infor
//counter counts the number of papers f
var counter = 0;
if (intent == "Default Welcome Intent") {
var greetings = ["Eita da!🤜🤛", "Wola Wops,😎", "Sharp fede!🤙","What's up my G!🤗"];
var plug =[
"*N.B: Remember to save this number*",
"*P.S: Click this link to share Msizi* : https://bit.ly/Msizi_share",
"*N.B: You can save & share this number!*",
"*Click this link to share Msizi* : https://bit.ly/Msizi_share",
"Try typing *_IGCSE Physics Past Papers_* to go straight to that option"
];
//finalResponse += "Wola Wops! I'm Msizi, I help with information about Education. \n\n To use me *choose one of the options below*:\n\n1 Past Papers\n2 Scholarships\n3 Opportunities \n5 Quiz \n\n*P.S: Click this link to share Msizi : http://bit.ly/Msizi_share*\n\n _To report issues_ : bit.ly/2H5b77q";
https.get('https://api.airtable.com/v0/appRAe4mxfGI1VDl6/users?api_key=keynre40bTqHjQ7AD', (resp) => {
var data;
var name;
var length;
resp.on('data', (chunk) => {
data = JSON.parse(chunk);
length = data.records.length;
var numberUsers = 0;
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
for(var i = 0 ; i < data.records.length ; i++){
var timer = JSON.stringify(data.records[i].createdTime.slice(0,10)).replace(/"/g, "");
if(timer == today){
numberUsers++;
}
}
finalResponse += greetings[Math.floor(Math.random() * greetings.length)];
finalResponse += "😎Msizi here, I help with information about Education.";
finalResponse += "\n\n*Choose one of the options below*:\n\n1 Past Papers\n2 Scholarships\n3 Opportunities \n5 Quiz\n\n";
/*switch (true) {
case (numberUsers < 20):
finalResponse += "❄️";
break;
case (numberUsers < 40):
finalResponse += "🌊";
break;
case (numberUsers < 60):
finalResponse += "🌡️";
break;
case (numberUsers < 80):
finalResponse += "♨️";
break;
case (numberUsers < 100):
finalResponse += "🔥";
break;
default:
alert("none");
break;
}
finalResponse += "User streak: "+numberUsers+"\n\n";*/
finalResponse += plug[Math.floor(Math.random() * plug.length)];
finalResponse += "\n\n _report issues_ : https://bit.ly/2H5b77q";
console.log("this is what we want:"+finalResponse)
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
response.send({
"fulfillmentText": finalResponse
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});
}
else if (intent == "past_paper") {
//response.send({"fulfillmentText": 'You want past papers'});
https.get('https://api.airtable.com/v0/appRAe4mxfGI1VDl6/past_papers?api_key=keynre40bTqHjQ7AD', (resp) => {
var data;
var name;
var length;
resp.on('data', (chunk) => {
data = JSON.parse(chunk);
length = data.records.length;
finalResponse += '*'+parameters.sylType+' '+parameters.paperType+' past papers* \n\n';
finalResponse += 'CLICK ON THE LINKS TO DOWNLOAD '+parameters.sylType.toUpperCase()+' PAPERS\n\n';
if(parameters.sylType == 'IGCSE'){
var subject = parameters.paperType;
var paperCode = {
'accounting' : ['0452',2,'Accounting','m'],
'math' : ['0580',4,'Mathematics','m'],
'admath' : ['0606',2,'Mathematics%20-%20Additional','m'],
'biology' : ['0610',6,'Biology','m'],
'physics' : ['0625',3,'Physics','m'],
'history' : ['0470',2,'History','s'], //add s &
'geography' : ['0460',2,'Geography','s'], //needs to be checked
'economics' : ['0455',2,'Economics','s'],
'food&nutrition' : ['0648',1,'Food%20and%20Nutrition','s'],
'chemistry' : ['0620',6,'Chemistry','m'],//return
'english' : ['0500',3,'English%20-%20First%20Language','m'],
'english literature' : ['0486',4,'English%20–%20Literature%20(English)','m'],
'business studies' : ['0450',2,'Business%20Studies','s']
}
for(var startYear = 15; startYear < 18; startYear++){
for(var counter2=1; counter2 <= paperCode[subject][1]; counter2++){
finalResponse += "20"+startYear+" : Paper "+counter2+" : "+'\nhttps://papers.xtremepapers.xyz/CIE/IGCSE/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_qp_'+counter2+'2.pdf\n';
finalResponse += "20"+startYear+" : Paper "+counter2+" *Markscheme* : "+'\nhttps://papers.xtremepapers.xyz/CIE/IGCSE/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_ms_'+counter2+'2.pdf\n';
}
finalResponse +='\n\n';
}
}
if(parameters.sylType == 'A Levels'){
var subject = parameters.paperType;
var paperCode = {
'accounting' : ['9706',3,'Accounting','m'],
'math' : ['9709',7,'Mathematics','m'],
'biology' : ['9700',2,'Biology','m'],
'physics' : ['9702',2,'Physics','m'],
'history' : ['9389',4,'History','s'], //add s &
'geography' : ['9696',3,'Geography','s'], //needs to be checked
'economics' : ['9708',4,'Economics','s'],//nope
'chemistry' : ['9701',2,'Chemistry','m']
}
if(paperCode[subject] == undefined){
finalResponse += 'Looks like I dont have those past papers yet. \n\n Click here to make a request: http://bit.ly/Request_Paper';
}
else{
//check if it exits
for(var startYear = 16; startYear < 18; startYear++){
for(var counter2=1; counter2 <= paperCode[subject][1]; counter2++){
finalResponse += "20"+startYear+" : Paper "+counter2+" : "+'\nhttps://papers.xtremepapers.xyz/CIE/AS%20and%20A%20Level/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_qp_'+counter2+'2.pdf\n';
finalResponse += "20"+startYear+" : Paper "+counter2+" *Markscheme* : "+'\nhttps://papers.xtremepapers.xyz/CIE/AS%20and%20A%20Level/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_ms_'+counter2+'2.pdf\n';
}
finalResponse +='\n\n';
}
}
}
if(parameters.sylType == 'Trial'){
finalResponse += "We have entered the trial zone!\n\n";
var subject = parameters.paperType;
var paperCode = {
'accounting' : ['0452',2,'Accounting','m'],
'math' : ['0580',4,'Mathematics','m'],
'admath' : ['0606',2,'Mathematics%20-%20Additional','m'],
'biology' : ['0610',6,'Biology','m'],
'physics' : ['0625',3,'Physics','m'],
'history' : ['0470',2,'History','s'], //add s &
'geography' : ['0460',2,'Geography','s'], //needs to be checked
'economics' : ['0455',2,'Economics','s'],
'food&nutrition' : ['0648',1,'Food%20and%20Nutrition','s']//return
}
for(var startYear = 15; startYear < 18; startYear++){
for(var counter2=1; counter2 <= paperCode[subject][1]; counter2++){
var url = 'https://papers.xtremepapers.xyz/CIE/IGCSE/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_qp_'+counter2+'2.pdf';
bitly.shorten(url)
.then(function(result) {
console.log(result);
finalResponse += result;
})
.catch(function(error) {
console.error(error);
});
//finalResponse += "20"+startYear+" : Paper "+counter2+" : "+'\nhttps://papers.xtremepapers.xyz/CIE/IGCSE/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_qp_'+counter2+'2.pdf\n' ;
finalResponse += "20"+startYear+" : Paper "+counter2+" *Markscheme* : "+'\nhttps://papers.xtremepapers.xyz/CIE/IGCSE/'+paperCode[subject][2]+'%20('+paperCode[subject][0]+')/'+paperCode[subject][0]+'_'+paperCode[subject][3]+''+startYear+'_ms_'+counter2+'2.pdf\n';
}
finalResponse +='\n\n';
}
}
if(parameters.sylType != 'IGCSE' && parameters.sylType != 'Trial' && parameters.sylType != 'A Levels') {
if (parameters.sylType == 'IEB') {
finalResponse += '_Please note: IEB papers do not have Memos or Markshemes_ \n';
}
//find the papers
for (var i = 0; i < length; i++) {
if (parameters.sylType == data.records[i].fields.Syllabus && data.records[i].fields.Name == parameters.paperType) {
var year = JSON.stringify(data.records[i].fields.Year);
finalResponse += year.replace(/"/g, "");
finalResponse += " : Paper ";
var paper = JSON.stringify(data.records[i].fields.PaperNumber);
finalResponse += paper.replace(/"/g, "");
finalResponse += " : ";
var link = JSON.stringify(data.records[i].fields.Link);
finalResponse += link.replace(/"/g, "");
finalResponse +="\n";
//counter counts the number of papers f
counter++;
}
}
if(counter == 0){
finalResponse += 'Looks like I dont have those past papers yet. \n\n Click here to make a request: http://bit.ly/Request_Paper';
}
}
finalResponse += "\n----------\nType *Quiz* to test your general knowledge \nType *Hi* to return to menu \n----------\n";
finalResponse += "_Service brought to you by_ *The Knowledge Institute*: http://bit.ly/2VhRCS6";
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
response.send({
"fulfillmentText": finalResponse
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});
}
else if (intent == "scholarship") {
//response.send({"fulfillmentText": 'You want scholarships'});
https.get('https://api.airtable.com/v0/appRAe4mxfGI1VDl6/scholarships?api_key=keynre40bTqHjQ7AD', (resp) => {
var data;
var name;
var length;
resp.on('data', (chunk) => {
data = JSON.parse(chunk);
length = data.records.length;
var scholarshipType = parameters.scholarshipType;
finalResponse += "Voila!😊😊😊 *"+scholarshipType+"* scholarships students can apply to : \n \n";
//First 5 scholarship
for (var j = 0; j < length; j++) {
//if(scholarshipType != 'all' || scholarshipType != '' || scholarshipType != undefined){
var level = JSON.stringify(data.records[j].fields.Level);
level = level.replace(/"/g, "");
if(level != scholarshipType && level != 'all'){
continue;
}
//}
var scholarName = JSON.stringify(data.records[j].fields.Name);
scholarName = scholarName.replace(/"/g, "");
console.log(scholarName)
//description
var desc = JSON.stringify(data.records[j].fields.Description);
desc = desc.replace(/"/g, "");
//link
var link = JSON.stringify(data.records[j].fields.Link2);
link = link.replace(/"/g, "");
//deadline
var deadline = JSON.stringify(data.records[j].fields.Deadline);
deadline = deadline.replace(/"/g, "");
//find number of days left
var DaysLeft = deadline.replace("-",",");
DaysLeft = deadline.replace("-",",");
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date();
var firstDate = new Date(DaysLeft);
var diffDays = Math.floor((firstDate.getTime() - secondDate.getTime())/(oneDay));
if(diffDays < 1){
continue;
console.log('we moved on')
}
finalResponse += "*" + scholarName + "*\n" + desc + " \n" +deadline+" | _"+diffDays+" days left_"+" | "+link;
finalResponse += "\n\n";
}
finalResponse += "\n----------\nType *Quiz* to test your general knowledge \nType *Hi* to return to menu \n----------\n";
finalResponse += "_Service brought to you by_ *The Knowledge Institute*: http://bit.ly/2VhRCS6";
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
response.send({
"fulfillmentText": finalResponse
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});
}
else if (intent == "opportunity") {
https.get('https://api.airtable.com/v0/appRAe4mxfGI1VDl6/opportunities?api_key=keynre40bTqHjQ7AD', (resp) => {
var data;
var name;
var deadline;
var length;
resp.on('data', (chunk) => {
data = JSON.parse(chunk);
length = data.records.length;
console.log("length: " + length);
//Here are some.....opportunities
finalResponse += "Here is a list of opportunities for young Africans including eSwatini. Click each for details! \n \n";
//show opportunities
for (var j = 0; j < length; j++) {
//the opportunity
var oppoName = JSON.stringify(data.records[j].fields.Name).trim();
oppoName = oppoName.replace(/"/g, "");
//the description
var description = JSON.stringify(data.records[j].fields.Description).trim();
description = description.replace(/"/g, "");
//link
var link = JSON.stringify(data.records[j].fields.Link).trim();
link = link.replace(/"/g, "");
//date
var deadline = JSON.stringify(data.records[j].fields.Deadline).trim();
deadline = deadline.replace(/"/g, "");
//find number of days left
var DaysLeft = deadline.replace("-",",");
DaysLeft = deadline.replace("-",",");
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date();
var firstDate = new Date(DaysLeft);
var diffDays = Math.floor((firstDate.getTime() - secondDate.getTime())/(oneDay));
if(diffDays < 1){
continue;
}
finalResponse += "*" + oppoName + "*\n"+description+"\n"+"Deadline: "+deadline+" | _"+diffDays+" days left_ | " + link;
finalResponse += "\n\n";
}
finalResponse += "\n----------\nType *Quiz* to test your general knowledge \nType *Hi* to return to menu \n----------\n";
finalResponse += "_Service brought to you by_ *The Knowledge Institute*: http://bit.ly/2VhRCS6";
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
response.send({
"fulfillmentText": finalResponse
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});
}
else if (intent == "apply") {
finalResponse += "well then!";
var pupu = " ";
var name = parameters.name;
name = name.replace(" ", "%20");
var email = parameters.email;
pupu = "https://airtable.com/shr0hQeky1xkRijiY?prefill_Name="+name+"&prefill_Email="+email+"&prefill_Cellphone="+p+" ";
response.send({
"fulfillmentText": pupu
});
}
else if (intent == "Quiz" || intent == "Quiz-Questions") {
var lifespan = request.body.queryResult.outputContexts[0].lifespanCount;
console.log('Lifespan is: ' + lifespan);
var location = 5 - lifespan;
var userAnswer = request.body.queryResult.queryText;
if (lifespan === undefined) {
response.set(JSON.stringify({
"responseId": 0
})); // context output
response.send(JSON.stringify({
"fulfillmentText": '😊😊Nice one! \n\n Share Msizi to practise with your friends!🤼\n http://bit.ly/Msizi_share \n \n Type *Hello* to see what else I can do.'
}));
}
if (location === 0) {
var link = 'https://api.airtable.com/v0/appu4FQOCrxJ7ItVO/quiz_'+parameters.paperType+'?api_key=keynre40bTqHjQ7AD';
https.get(link, (resp) => {
var data = "";
let joe;
resp.on('data', (chunk) => {
joe = JSON.parse(chunk);
var sentence = JSON.stringify(joe.records[0].fields.Question);
sentence = sentence.split("<br>").join("\n");
var desired = sentence.replace(/"/g, "");
var length = joe.records.length;
for(i=0 ; i < length ; i++){
if(parameters.paperType == joe.records[i].fields.Subject){
console.log('this is it');
}
}
data += 'Welcome to the '+parameters.paperType+' Quiz section \n_this is a multiple choice quiz_ \n Type *A B C D* ONLY\n\n';
data += desired;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
//request.body.session = "+230_5778_1246";
response.send({
"fulfillmentText": data
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});
}
else {
console.log('the second is:'+quizParameters[0].parameters.paperType)
https.get('https://api.airtable.com/v0/appu4FQOCrxJ7ItVO/quiz_'+quizParameters[0].parameters.paperType+'?api_key=keynre40bTqHjQ7AD', (resp) => {
var data = "";
let joe;
resp.on('data', (chunk) => {
joe = JSON.parse(chunk);
var sentence = JSON.stringify(joe.records[location].fields.Question);
sentence = sentence.split("<br>").join("\n");
var desired = sentence.replace(/"/g, "");
var correctAnswer = JSON.stringify(joe.records[location - 1].fields.Answer);
correctAnswer = correctAnswer.replace(/"/g, "");
//correctAnswer = correctAnswer.toUpperCase();
//what the person inputted
userAnswer = userAnswer.toUpperCase();
var userActualAnswer = JSON.stringify(joe.records[location - 1].fields[userAnswer]);
userActualAnswer = userActualAnswer.replace(/"/g, "");
//data += '\n \n The correct answer is '+userActualAnswer+'\n\n';
if (correctAnswer == userActualAnswer) {
data += '🤗🤗Nice one! That is correct \n \n ';
} else {
data += '🤢🤢Nah! The correct answer is ' + correctAnswer+'\n \n';
var explanation = JSON.stringify(joe.records[location-1].fields.explanation);
data += "_"+explanation+"_";
data += "\n";
data += "----------";
data += "\n";
}
data += desired;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
response.send({
"fulfillmentText": data
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
var issue = "Error: " + err.message;
response.send(JSON.stringify({
"fulfillmentText": issue
}));
});
}
}
else {
response.send({
"fulfillmentText": 'Looks like I dont know what you want!😐 '
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment