Conversations with Dialogflow and Express: Enhancing Fulfilment

I'm facing a challenge with receiving responses from dialogflow, even though other express calls are functioning properly.

I believe the issue lies within the agents, but I am unsure of the specific problem or how to resolve it. That's why I have turned to this platform for assistance.

Important points to keep in mind:

  • This code is being integrated into an existing, tested express application
  • Testing has been conducted using Postman
  • The Dialogflow fulfillment template webhook can be accessed here
  • The console successfully outputs We got hours!, but then stops
  • If you comment out lines 57 through 62 (the if section) and uncomment line 56, the code responds as expected
  • The issue is likely within the agents.hours function
  • I have also attempted to use this.currentlyOpen() === true

Many thanks in advance.

dialogflow.ts

// import { google } from 'googleapis';
const {WebhookClient} = require('dialogflow-fulfillment');
// import { Card, Suggestion } from 'dialogflow-fulfillment';
/**
 * @private
 * Initialise the ai assist api
 */
export class Agents {
  aiassist:any

  async initialize (message:any) {
    var aiassist = {
      info: {
        configsuccess: false,
        message: message,
        data: [],
      }
    }
    process.env.DEBUG = 'dialogflow:debug';
    const url = message.headers.configlocation;
    await message.core.request({url: url, json: true}, function (error: any, response: { statusCode: number; }, data: any) {
      aiassist.info.data = data
      if (!error && response.statusCode === 200) {
        aiassist.info.configsuccess = true
      }
      return aiassist
    })
    this.aiassist = aiassist
    this.WebhookProcessing();
  }

  /**
  * @private
  * Find the map the agent
  */
  WebhookProcessing () {
    const agent = new WebhookClient({request: this.aiassist.info.message.full, response: this.aiassist.info.message.res});

    let intentMap = new Map();
    intentMap.set('Hours', this.hours);

    agent.handleRequest(intentMap);
  }

  /****************
  * AGENT        *
  *  DECLARATION *
  ****************/
  /**
  * [hours description]
  * @param  agent [description]
  * @return       [description]
  */
  hours (agent:any) {
    console.log("We got hours!")
    // agent.add(`We're open now! We close at 17:00 today. Is there anything else I can help you with?`);
    if (currentlyOpen(this.aiassist)) { // TypeError: Cannot read property 'aiassist' of undefined
      console.log("open!")
      agent.add(`We're open now! We close at 17:00 today. Is there anything else I can help you with?`);
    } else {
      console.log("closed!")
    }
  }

}

/******************
* FUNCTIONS      *
*    DECLARATION *
******************/

//  Check if currently open - Issues getting "aiassist" into this function
function currentlyOpen (aiassist:any) {
  // Get current datetime with proper timezone
  console.log("We got currentlyOpen!")
  // const date = new Date()
  console.log(aiassist.info.data.timeZoneOffset)
  // console.log("We finished currentlyOpen")
  // date.setHours(date.getHours() + parseInt(agent.this.aiassist.info.data.timeZoneOffset.split(':')[0]));
  // date.setMinutes(date.getMinutes() + parseInt(agent.this.aiassist.info.data.timeZoneOffset.split(':')[0][0] + agent.this.aiassist.info.data.timeZoneOffset.split(':')[1]));
  // return date.getDay() >= 1 &&
  // date.getDay() <= 5 &&
  // date.getHours() >= agent.this.aiassist.info.data.businessSetings.openTime &&
  // date.getHours() <= agent.this.aiassist.info.data.businessSetings.closeTime;
  return true
}   
TypeError: Cannot read property 'aiassist' of undefined
  File "C:\Users\sjona\Desktop\TSC\repo\curr\built\routes\v1\dialogflow.js", line 53, col 32, in hours
    if (currentlyOpen(this.aiassist)) {
  File "C:\Users\sjona\Desktop\TSC\repo\curr\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js", line 313, col 44, in WebhookClient.handleRequest
    let result = handler.get(this.intent)(this);
  File "C:\Users\sjona\Desktop\TSC\repo\curr\built\routes\v1\dialogflow.js", line 39, col 15, in Agents.WebhookProcessing
    agent.handleRequest(intentMap);
  File "C:\Users\sjona\Desktop\TSC\repo\curr\built\routes\v1\dialogflow.js", line 29, col 14, in Agents.initialize
    this.WebhookProcessing();

UPDATE: Revised code to align with comments. Noted where challenges are arising.

Answer №1

The issue arises because this is not what you anticipate it to be due to how hours() is invoked and the varying meanings of this based on its context. For more information, refer to this page.

  • When a function is called, this refers to the global object rather than the lexically bound version of this (i.e., the value of this inside a class).
  • To access the lexically bound version of this, you must bind the value to the function using bind() or utilize an arrow function for the call.

In your specific scenario, it is advisable to register the Intent Handler as follows:

intentMap.set('Hours', agent => this.hours(agent));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble locating modules or properties with ANTLR4 TypeScript target?

Having reached a frustrating impasse, I am seeking assistance with a perplexing issue. My attempt to integrate TypeScript with ANTLR4 has hit a snag, and despite exhaustive efforts, I am unable to pinpoint the root cause (with limited documentation availab ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

Error in TypeScript: The object may be null when using the window.open method

Is there a way to implement this code in Typescript? window.open(externalUrl, '_blank').focus(); Encountering the following TypeScript error: Object is possibly 'null'.ts(2531) I attempted the following solution without success: ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...

Having difficulty mastering the redux-form component typing

I am facing an issue while trying to export my component A by utilizing redux-form for accessing the form-state, which is primarily populated by another component. During the export process, I encountered this typing error: TS2322 Type A is not assignabl ...

Strategies for managing multiple request keys that share the same value

In the process of this project, I am creating models and passing values from a POST request's body. My main objective is to properly define these models. Here is a JSON sample that I intend to post to MongoDB: { "signageId": "5cd857c4965f863b7c8 ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

Error encountered during conversion from JavaScript to TypeScript

I am currently in the process of converting JavaScript to TypeScript and I've encountered the following error: Type '(props: PropsWithChildren) => (any[] | ((e: any) => void))[]' is not assignable to type 'FC'. Type '(a ...

Error: When using Express with sqlite3, a TypeError occurs due to the inability

I've been working on displaying data from an sqlite3 database on a web page within my Express application. In my route file, here is what I have: var express = require('express'); var router = express.Router(); var fs = require("fs"); var ...

Make a post request to an Express server without modifying the URL

I'm currently working on a login form that uses angularjs' ng-submit feature. My goal is to trigger a post method call to the server without altering the URL when the submit button is clicked. Express's post function necessitates a specific ...

Passing the socket.io instance to an express route

I am currently working on developing a nodejs application that will utilize various web APIs to search for information. The goal is to send the results to the client in real-time using socket.io, with jQuery handling the front end display of the data. Wha ...

Vitest surpasses Jest by providing explicit type declarations, ensuring no more "unknown type" errors

Transitioning from Jest to vitest has been a smooth process for me. I'm currently in the midst of converting the following code snippets: // Jest const myLib = jest.requireActual("mylib.js") to this: // Vitest const myLib = await vi.importA ...

Troubleshooting Login Issues with ExpressJS, NodeJs, and Redis

I'm having an issue with validating the username and password in Redis, as it keeps showing that they are undefined. I am seeking assistance in resolving this problem within NodeJs/ExpressJs. CODE: app.js var express = require('express'); ...

Dealing with Scope Limitations in Express.js with the 'express-oauth2-jwt-bearer' Package: An Auth0 Dilemma

I am in the process of setting up a private-scoped endpoint on my Express.js backend API for verifying custom permissions. In this setup, I am utilizing RBAC (Role-Based Access Control) through auth0 with the 'express-oauth2-jwt-bearer' package. ...

Trouble with accessing Dynamic StyleSheet properties based on type restrictions

I have successfully developed a functional component in React Native that supports both light and dark theme styles. const lightThemeOverrides = StyleSheet.create({ <light_override_styles_here> }); const styles = StyleSheet.create({ <styles_here&g ...

Arrangement of gaming activities within a fast-paced express.js application

Operating a server hosting multiple multiplayer web games utilizing Node.js+Express.js can be quite the task. The current setup involves a standard folder structure, with Jade files stored under "views", client-side Javascript files tucked away in "public/ ...

Utilizing the Bootstrap 5 Alpha validation script within a React environment

I've been working on implementing Bootstrap 5 alpha's validation in my React app. https://i.sstatic.net/tbqLr.png The form should not submit if left blank, and it should display a check or an error mark at the bottom accordingly. So far, I&apo ...

Angular 4 Web Application with Node-Red for Sending HTTP GET Requests

I am creating a unique service that utilizes Node-red to send emails only when a GET request is made to 127.0.0.1:1880/hello (node-red port), and an Angular 4 web app (127.0.0.1:3000) for client access. Upon accessing the /hello page from a browser, I rec ...