Ошибка: входящий объект JSON не содержит поле client_email в JWT.fromJSON - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь настроить мессенджер-бот с Dialogflow, и я нахожу этот учебник в сети: https://blog.pusher.com/facebook-chatbot-dialogflow/

Я выполнил шаги, чтобы настроить webhook, создать свой проверьте токен, разрешите моей странице Facebook подписаться на него, выставьте мой сервер на ngrok и настройте некоторые намерения в Dialogflow.

Но когда я пытаюсь отправлять сообщения, консоль моего webhook показывает сообщение об ошибке, подобное этому:

ERROR: Error: The incoming JSON object does not contain a client_email field
    at JWT.fromJSON (C:\Users\user\Desktop\MessageBot_DialogFlow\node_modules\google-auth-library\build\src\auth\jwtclient.js:193:19)
    at GoogleAuth._cacheClientFromJSON (C:\Users\user\Desktop\MessageBot_DialogFlow\node_modules\google-auth-library\build\src\auth\googleauth.js:313:16)
    at GoogleAuth.getClient (C:\Users\user\MessageBot_DialogFlow\node_modules\google-auth-library\build\src\auth\googleauth.js:494:22)
    at GrpcClient._getCredentials (C:\Users\user\MessageBot_DialogFlow\node_modules\google-gax\build\src\grpc.js:92:40)
    at GrpcClient.createStub (C:\Users\user\MessageBot_DialogFlow\node_modules\google-gax\build\src\grpc.js:213:34)
    at new SessionsClient (C:\Users\user\MessageBot_DialogFlow\node_modules\dialogflow\src\v2\sessions_client.js:159:34)
    at Object.<anonymous> (C:\Users\user\MessageBot_DialogFlow\src\process-message.js:17:23)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)

Я не уверен, что в моем «процессе-сообщении» есть ошибка. Вот мой код:

const fetch = require('node-fetch');

// You can find your project ID in your Dialogflow agent settings
const projectId = 'messangerbot-fljyhy'; //https://dialogflow.com/docs/agents#settings
const sessionId = '123456';
const languageCode = 'en-US';

const dialogflow = require('dialogflow');

const config = {
    credentials: {
        private_key: process.env.DIALOGFLOW_PRIVATE_KEY,
        client_email: process.env.DIALOGFLOW_CLIENT_EMAIL
    }
};

const sessionClient = new dialogflow.SessionsClient(config);

const sessionPath = sessionClient.sessionPath(projectId, sessionId);

// Remember the Page Access Token you got from Facebook earlier?
// Don't forget to add it to your `variables.env` file.
const { FACEBOOK_ACCESS_TOKEN } = process.env;

const sendTextMessage = (userId, text) => {
    return fetch(
        `https://graph.facebook.com/v2.6/me/messages?access_token=${FACEBOOK_ACCESS_TOKEN}`,
        {
            headers: {
                'Content-Type': 'application/json',
            },
            method: 'POST',
            body: JSON.stringify({
                messaging_type: 'RESPONSE',
                recipient: {
                    id: userId,
                },
                message: {
                    text,
                },
            }),
        }
    );
}

module.exports = (event) => {
    const userId = event.sender.id;
    const message = event.message.text;

    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                text: message,
                languageCode: languageCode,
            },
        },
    };

    sessionClient
        .detectIntent(request)
        .then(responses => {
            const result = responses[0].queryResult;
            return sendTextMessage(userId, result.fulfillmentText);
        })
        .catch(err => {
            console.error('ERROR:', err);
        });
}

Я обнаружил, что есть некоторые аналогичные вопросы по stackoverflow, но большинство вопросов касаются firebase. Я не уверен, что это одни и те же вопросы, поэтому я просто отправляю еще один вопрос.

Вот содержимое моего пакета. json, может кто-нибудь сказать мне, где проблема? Спасибо.

{
  "name": "bot",
  "version": "1.0.0",
  "description": "n",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/nick880107-git/ProjectBot.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/nick880107-git/ProjectBot/issues"
  },
  "homepage": "https://github.com/nick880107-git/ProjectBot#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "dialogflow": "^1.2.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "node-fetch": "^2.6.0"
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...