Не удалось позвонить через Webhook. Ошибка: 500 Внутренняя ошибка сервера | Dialogflow | Firebase - PullRequest
3 голосов
/ 20 марта 2019

Я пытаюсь создать функцию firebase для отправки ответа API в диалоговый поток, используя webhook выполнения, но я сталкиваюсь с ошибкой: 500.

const functions = require('firebase-functions');
var request = require('request')

exports.webhook = functions.https.onRequest((request, response) => {

        console.log("request.body.result.parameters: ", request.body.result.parameters);
        let params = request.body.result.parameters;

        var options = {
            url: `https://islam360api.herokuapp.com/${params.find}`,
            json:true
        }
        request(options, function(error, response, body){
            if(error) response.send(error);
            else response.send(body);
        });
    });

Предупреждение, которое я получил при развертывании:

  13:26  warning  Unexpected function expression  prefer-arrow-callback

✖ 1 problem (0 errors, 1 warning)
  0 errors and 1 warning potentially fixable with the `--fix` option.

например, если params.find равно evoke, то при анализе ответа API должен получиться

https://islam360api.herokuapp.com/evoke

{"speech":"In Surat-ul-Fateha, Ayat Number: 7, Quran says:  not of those who have evoked [Your] anger or of those who are astray. ","displayText":"In Surat-ul-Fateha, Ayat Number: 7, Quran says:  not of those who have evoked [Your] anger or of those who are astray. "}

Edit: Это ответ, который я получаю при развертывании функции firebase

C:\Users\mnauf\Desktop\IOT\islam360\firebase>firebase deploy --only functions

=== Deploying to 'islam360-3cf18'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint C:\Users\mnauf\Desktop\IOT\islam360\firebase\functions
> eslint .


C:\Users\mnauf\Desktop\IOT\islam360\firebase\functions\index.js
  13:26  warning  Unexpected function expression  prefer-arrow-callback

✖ 1 problem (0 errors, 1 warning)
  0 errors and 1 warning potentially fixable with the `--fix` option.

+  functions: Finished running predeploy script.
i  functions: ensuring necessary APIs are enabled...
+  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (37.98 KB) for uploading
+  functions: functions folder uploaded successfully
i  functions: updating Node.js 6 function webhook(us-central1)...
+  functions[webhook(us-central1)]: Successful update operation.

+  Deploy complete!

Please note that it can take up to 30 seconds for your updated functions to propagate.
Project Console: https://console.firebase.google.com/project/islam360-3cf18/overview

Журналы

ОТВЕТ RAW API

{
  "id": "ed1108a6-a938-4cfb-8fe1-7a1fa0c856e4",
  "timestamp": "2019-03-20T18:02:22.676Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "where does Quran talk about evoke",
    "action": "",
    "actionIncomplete": false,
    "parameters": {
      "find": "evoke"
    },
    "contexts": [],
    "metadata": {
      "isFallbackIntent": "false",
      "webhookResponseTime": 129,
      "intentName": "find",
      "intentId": "dd549c44-25bd-48fa-915f-4810759968eb",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false"
    },
    "fulfillment": {
      "speech": "Something went wrong",
      "messages": [
        {
          "type": 0,
          "speech": "Something went wrong"
        }
      ]
    },
    "score": 1
  },
  "status": {
    "code": 206,
    "errorType": "partial_content",
    "errorDetails": "Webhook call failed. Error: 500 Internal Server Error"
  },
  "sessionId": "4d887eaa-2dc1-649d-9ae6-238a6d79f085"
}

ЗАПРОС ВЫПОЛНЕНИЯ

{
  "id": "ed1108a6-a938-4cfb-8fe1-7a1fa0c856e4",
  "timestamp": "2019-03-20T18:02:22.676Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "where does Quran talk about evoke",
    "action": "",
    "actionIncomplete": false,
    "parameters": {
      "find": "evoke"
    },
    "contexts": [],
    "metadata": {
      "isFallbackIntent": "false",
      "webhookResponseTime": 129,
      "intentName": "find",
      "intentId": "dd549c44-25bd-48fa-915f-4810759968eb",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false"
    },
    "fulfillment": {
      "speech": "Something went wrong",
      "messages": [
        {
          "type": 0,
          "speech": "Something went wrong"
        }
      ]
    },
    "score": 1
  },
  "status": {
    "code": 206,
    "errorType": "partial_content",
    "errorDetails": "Webhook call failed. Error: 500 Internal Server Error"
  },
  "sessionId": "4d887eaa-2dc1-649d-9ae6-238a6d79f085"
}

ОТВЕТ НА ВЫПОЛНЕНИЕ

Error: could not handle the request

СТАТУС ВЫПОЛНЕНИЯ

Webhook call failed. Error: 500 Internal Server Error

Снимок экрана консоли

enter image description here

Журналы Firebase

enter image description here

Из журналов Firebase, похоже, я должен заплатить. Должен ли я?

1 Ответ

3 голосов
/ 20 марта 2019

если вы используете dialogflow v2:

 request(options, function(error, response, body){
     if(error) 
         response.send({ fulfillmentText: "error in api call"});
     else 
         response.send({ fulfillmentText: body.speech });
 });

если вы используете dilogflow v1 (скоро будет устаревшим)

 request(options, function(error, response, body){
     if(error) 
         response.send({ speech: "error in api call"});
     else 
         response.send({ speech: body.speech });
 });

для проверки / изменения версиидиалогового окна, перейдите к консоли dilogflow (https://console.dialogflow.com), нажмите значок шестеренки и проверьте его в общем разделе, не забудьте нажать кнопку сохранения на случай, если вы ее измените

Обновление

Согласноваша функция Firebase регистрирует да, вам нужно заплатить,

Обратите внимание, что функции Firebase позволяют только вызывать только API Google и не позволяют сторонним API в бесплатной квоте, вам нужно переместить свой план на "оплату"по ходу дела », так как он самый дешевый среди всех

В качестве альтернативы вы можете использовать экспресс-сервер для создания веб-крюка и развернуть его в облаке heroku, они позволяют сторонним вызовам API в их бесплатном плане

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...