Skip to content

Instantly share code, notes, and snippets.

@CedricL46
Last active April 25, 2018 11:57
Show Gist options
  • Save CedricL46/477a3f62a64fca385afd593af79633b2 to your computer and use it in GitHub Desktop.
Save CedricL46/477a3f62a64fca385afd593af79633b2 to your computer and use it in GitHub Desktop.
const botBuilder = require("claudia-bot-builder");
const fbTemplate = botBuilder.fbTemplate;
//to install run 'npm i sync-request' in the project folder terminal
var request = require("sync-request");
//to install run 'npm i keyword-extractor' in the project folder terminal
var keywordExtractor = require("keyword-extractor");
//function to query the really nice icanhazdadjoke API for a joke
function getJoke(keyword) {
var res = request("GET", "https://icanhazdadjoke.com/search", {
headers: {
Accept: "text/plain"
},
qs: { term: String(keyword), limit: "1" }
});
return res.getBody("utf8");
}
function getRandomJoke() {
var res = request("GET", "https://icanhazdadjoke.com/", {
headers: {
Accept: "text/plain"
}
});
return res.getBody("utf8");
}
module.exports = botBuilder(message => {
if (message.type === "facebook") {
// Extract the keywords from the user typed message
var keywords = keywordExtractor.extract(message.text, {
language: "english",
remove_digits: true,
return_changed_case: true,
remove_duplicates: true
});
//get the last typed keyword that we can use
let keyword = keywords[keywords.length - 1];
if (keyword && (keyword.toUpperCase() === "JOKE" || keyword.toUpperCase() === "JOKES")) {
keyword = keywords[keywords.length - 2];
}
if (keyword) {
// get joke from the last found keywords
let resultJoke = getJoke(keyword);
if (resultJoke) {
// return the response animated
return ["Hum do I have a joke about " + keyword + "...", new fbTemplate.ChatAction("typing_on").get(), new fbTemplate.Pause(500).get(), resultJoke];
} else {
let randomJoke = getRandomJoke();
return ["Well i couldn't find a joke about " + keyword + " so here is a random joke : ", new fbTemplate.ChatAction("typing_on").get(), new fbTemplate.Pause(300).get(), randomJoke];
}
} else {
return [new fbTemplate.ChatAction("typing_on").get(), new fbTemplate.Pause(300).get(), "Brrrr, what was that ? I don't understand those gimish ! Could you try something else ? "];
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment