The cloud function in Firebase was unable to connect to the dialogflow route

I am currently working on creating a chatbot using Dialogflow integrated with OpenAI in Firebase Cloud Function. However, I am facing an issue where I cannot access the /dialogflow endpoint and keep receiving the error message: "Cannot GET /dialogflow". My project is built using Node.js and all other routes seem to be functioning properly. I have split my code into three files - app.js, server.js, and index.js. Any assistance with this would be greatly appreciated. Here is the snippet of my code:

const functions = require("firebase-functions");
const {Configuration, OpenAIApi} = require("openai");
require("dotenv").config();

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const express = require("express");
const {WebhookClient} = require("dialogflow-fulfillment");
const app = express();

app.get("/", (req, res) => res.send("online"));
app.post("/dialogflow", express.json(), (req, res) => {
  const prompt = new WebhookClient({request: req, response: res});

  /**
 * A function to welcome the user to the agent.
 * @param {Object} agent - The Dialogflow agent object.
 */
  function welcome() {
    prompt.add("Welcome to my agent!");
  }
  
  async function queryGPT(prompt) {
    try {
      const response = await openai.createCompletion({
        model: "text-davinci-003",
        prompt: `Human: ${prompt}\nAI: `,
        temperature: 0.9,
        max_tokens: 500,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0.6,
        stop: ["Human:", "AI:"],
      });

      return {
        status: 1,
        response: `${response.data.choices[0].text}`,
      };
    } catch (error) {
      return {
        status: 0,
        response: "",
      };
    }
  }

  const intentMap = new Map();
  intentMap.set("Default Welcome Intent", welcome);
  intentMap.set("Default Fallback Intent", queryGPT);
  prompt.handleRequest(intentMap);
});

module.exports = app;

Code snippet for server.js :

const app = require("./app");

app.listen(process.env.PORT || 8080);

Code snippet for Index.js

const functions = require("firebase-functions");
const app = require("./app");

exports.app = functions.https.onRequest(app);

Answer №1

Your /chatbot endpoint is configured to handle POST requests:

app.post("/chatbot", express.json(), (req, res) => { ... }

Please note that it is not designed to work with GET requests.

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

Tips for toggling the display of multiple ion-input fields based on the selected value from an ion-select dropdown

I am working with an ion-select element that contains options from 1 to 10. <ion-label> Select how many input fields</ion-label> <ion-select> <ion-option value="0"> Zero</ion-option> <ion-option value="1"> One</ion- ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

The Splice function is malfunctioning due to issues with the object (the indexOf function is not recognized)

I am currently dealing with an object that looks like this: Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"} My goal is to remove any keys within the object that have empty values (""). I attempted the following code snippet: ...

I'm experiencing issues with the partial text search feature on my express application

Presently, I am utilizing the following route for a text search. router.post("/visit", middleware.isLoggedin, function(req,res){ subject.find({Subject_Name: req.body.user} ).sort('Visit_date').exec(function(err,returnedsubjects){ if( ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...

Show the value in the input text field if the variable is present, or else show the placeholder text

Is there a ternary operator in Angular 1.2.19 for templates that allows displaying a variable as an input value if it exists, otherwise display the placeholder? Something like this: <input type="text "{{ if phoneNumber ? "value='{{phoneNumber}}&a ...

where is the yarn global registry located?

After updating yarn to point to my custom registry and verifying the changes, here is what I found: $yarn config list -g yarn config v1.22.10 info yarn config { 'version-tag-prefix': 'v', 'version-git-tag': true, ' ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

Unable to hear sound properly through Web Audio

I'm experimenting with playing a wav file using the AudioContext. I've noticed that it plays correctly when loaded with the <audio> tag (as demonstrated in this example on jsFiddle), but encounters issues when using AudioContext. var startB ...

Exploring the Function Scope within ViewModel

I have been facing an issue while trying to call a function from my ViewModel within a foreach loop. It seems like the function goes out of scope as soon as I call it. Being new to JavaScript, I am struggling to understand why this is happening. Here is t ...

The power of MobX lies in its ability to provide a deep

I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below. Can someone point me in the rig ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Adding an image to a PDF file using NodeJS and Pdfmake

I am currently using the pdfmake api in my NodeJS application to generate PDF files. However, I am facing an issue when trying to add an image to the document as I keep receiving the following error message: Error: Invalid image format. The images dictiona ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

What is the process for incorporating additional fields into Firebase?

I am looking to incorporate a fresh field similar to the example shown below, but I am unsure of how to proceed. In my previous attempt, I utilized a method called {merge: true}, yet encountered no success with resolving the issue at hand. Whenever I inp ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...