🕹Creating HayWord Feature

this time we will create a HayWord feature by attracting users to guess the word based on definitions, synonyms, and word types.

Creating HayWord Menu With Generic Templates#

menu_hayword

  1. Create a menuPayload variable for the menu template with Generic type.

    let menuPayload = {
    attachment:{
    type:"template",
    payload:{
    template_type:"generic",
    elements:[
    {
    title:"HayWord",
    image_url:"https://res.cloudinary.com/dzrwauiut/image/upload/v1603631463/HayWord_qj0hzv.png", //thumbnail image
    subtitle:"enrich your vocabulary through a fun way",
    buttons:[
    {
    type:"postback",
    title:"🕹 Play",
    payload:"PLAY_HAYWORD" //postback
    }
    ]
    }
    ]
    }
    }
    }
    Show Details

    menuPayload

tip

Find more Message template here

  1. Add menu instructions when the user is done saving their profile.

    //when the user saves the profile
    app.post("/setProfile", (req, res) => {
    console.log(req.body);
    db.doc(`users/${req.body.id}`)
    .update({
    language: `${req.body.lang}`
    })
    .then(function() {
    language = req.body.lang
    callSendAPI(req.body.id, {
    text: 'Your Profile has Updated' }
    //add instructions to use menus and translate to users
    .then(()=>{
    callSendAPI(req.body.id, {
    text: 'Type "menu" for accessing our feature or type "Translate <Word or Sentence that you want to translate to your language>"' } )
    })
    res.status(200).end();
    });
    });
    Show Details

    add_instructions

  2. Displays the menu template from menuPayload when the user types menu in messenger in the handleMessage function.

    else if(received_message.text.toLowerCase() == 'menu'){
    callSendAPI(sender_psid, menuPayload)
    }
    Show Details

    menu_Instruction

Using the WordsAPI#

Now we will use the API 'WordsAPI' in RapidAPI to translate the words that users input in the chat.

  1. Go to WordsAPI RapidAPI page, make sure you are logged in.

  2. Just like the steps for using Just Translated API, subscribe to the test > choose the basic plan.

  3. Copy the sample code provided by RapidAPI, on the right, select the programming language Node.js > Request.

    Show Details

    copy_wordsapi_code

  4. Create a getWord () function in the app.js file from the code previously copied to get the word the user will guess.

    function getWord() {
    return new Promise((resolve, reject) => {
    var options = {
    method: 'GET',
    url: 'https://wordsapiv1.p.rapidapi.com/words/',
    qs: {
    //take the word randomly
    random: 'true',
    //at least 4 letters of the word selected
    lettersMin: '4',
    //the maximum word selected is 8 letters
    lettersMax: '8',
    //word generality level of at least 4.05 and a maximum of 8.03
    frequencyMin: '4.05',
    frequencyMax: '8.03',
    //words have definite, word types, synonyms attributes
    hasDetails: 'definitions,partofspeech,synonyms'
    },
    headers: {
    'x-rapidapi-host': 'wordsapiv1.p.rapidapi.com',
    'x-rapidapi-key': process.env.RAPID_API_KEY,
    useQueryString: true
    }
    };
    request(options, function (error, response, body) {
    if (error) reject(error);
    const bodyParse = JSON.parse(body)
    console.log(bodyParse);
    const word = bodyParse.word;
    const def = bodyParse.results[0].definition || '';
    const wordType = bodyParse.results[0].partOfSpeech || '';
    const synonym = bodyParse.results[0].synonyms || '';
    //returns the value of the guessed word, definition, word type, and synonym
    resolve([word, def, wordType, synonym])
    });
    })
    }
  5. Create the var modeHayWord; var word; var def; var wordType; var synonym; var censored; var featureHayWord = []; globally.

    Show Details

    variabel_hayword

info

We need to make it globally because the variables will be accessed by different function and use it as a state.

  1. Create a PLAY_HAYWORD postback response to the handlePostback() function to call the getWord() function.

    //check if the payload is the same as PLAY_HAYWORD
    else if(payload === 'PLAY_HAYWORD'){
    //set the modeHayWord variable to true
    modeHayWord = true;
    //call getWord function
    getWord().then(data => {
    //assigns a value to the variable according to the data obtained from the getWord function
    word = data[0];
    def = data[1];
    wordType = data[2];
    synonym = data[3];
    //make word formatting visible at the beginning and end of letters eg F_ _ _ _ _ _ K (FACEBOOK)
    var regex = /(?<!^).(?!$)/g;
    censored = word.replace(regex, ' _ ')
    //create response quick replies as instructions for the user to guess the word
    if (wordType != '') {
    featureHayWord.push({
    content_type: "text",
    title: "Type of Word",
    payload: "WORD_TYPE",
    })
    }
    if (def != '') {
    featureHayWord.push({
    content_type: "text",
    title: "Definition",
    payload: "DEFINITION",
    })
    }
    if (synonym != '') {
    featureHayWord.push({
    content_type: "text",
    title: "Synonym",
    payload: "SYNONYM",
    })
    }
    featureHayWord.push({
    content_type: "text",
    title: "🥺 Surrender",
    payload: "SURR",
    })
    response = {text: censored, quick_replies: featureHayWord}
    return callSendAPI(sender_psid, response, "RESPONSE");
    })
    }

Provide Hints and Check User Answers#

now we will provide the hint to the user and check the user's answer whether it is right or wrong.

  1. Updated the handleMessage() function to add hint responses and answer results.

    async function handleMessage(sender_psid, received_message) {
    let response;
    // Checks if the message contains text
    if (received_message.text) {
    // Create the payload for a basic text message, which
    // will be added to the body of our request to the Send API
    console.log(received_message.nlp.entities);
    const objNlp = received_message.nlp.entities;
    if (
    objNlp.intent &&
    objNlp.intent[0].value == "translate" &&
    objNlp.intent[0].confidence > 0.8 &&
    objNlp.phrase_to_translate[0].confidence > 0.8
    ) {
    language = language
    ? language
    : await db
    .doc(`users/${sender_psid}`)
    .get()
    .then(docSnapshot => {
    if (docSnapshot.exists) {
    console.log("language from here");
    return docSnapshot.data().language;
    }
    });
    let tr = await translate(objNlp.phrase_to_translate[0].value, language);
    response = {
    text: tr
    };
    return callSendAPI(sender_psid, response);
    }
    else if(received_message.text.toLowerCase() == 'menu'){
    response = menuPayload
    return callSendAPI(sender_psid, response);
    }
    //check if the user is in a HayWord session
    if(modeHayWord){
    // give the user hints
    if(received_message.quick_reply){
    if(received_message.quick_reply.payload == 'WORD_TYPE'){
    response = {text: wordType}
    }
    else if(received_message.quick_reply.payload == 'DEFINITION'){
    response = {text: def}
    }else if (received_message.quick_reply.payload == "SYNONYM") {
    response = { text: synonym };
    }else if (received_message.quick_reply.payload == "SURR") {
    featureHayWord = []
    return callSendAPI(sender_psid, { text: "the Answer is "+word }).then(() =>
    callSendAPI(sender_psid, {text: 'don\'t give up 💪'})
    );
    }
    return callSendAPI(sender_psid, response);
    }
    else if(received_message.text){
    //check the user's answer whether it is correct or not
    if(received_message.text.toLowerCase()== word){
    modeHayWord = false;
    featureHayWord = []
    response = { text: 'Right Answer '}
    return callSendAPI(sender_psid, response);
    }
    else{
    response = {text: censored, quick_replies: featureHayWord}
    return callSendAPI(sender_psid, {text: 'Wrong Answer'}).then(()=> callSendAPI(sender_psid,response,"RESPONSE"))
    }
    }
    }
    }
    }