Search code examples
node.jsfacebookfacebook-graph-apiapi-aifacebook-webhooks

Socket hang up exception on Facebook Graph Api on POST call to messages using nodejs


Following is the code i am using to send response of message in nodejs (express) app, which is subscribed to webhooks.

I am getting successful random messages from apiAiClient on sending any from the message on the Fb Messenger from the fb page, but its post call back to the fb page throws the following error:

{ Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1135:19)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at TLSSocket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
code: 'ECONNRESET',
path: null,
host: 'graph.facebook.com',
port: 443,
localAddress: undefined }

Below is the code to send post call to facebook api:

const sendTextMessage = (senderId, text) => {
  let req = {
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: FACEBOOK_ACCESS_TOKEN },
    method: 'POST',
    json: {
      messaging_type: "UPDATE",
      recipient: { id: senderId },
      message: { text: text }
    }
  };
  request(req, response => {
    console.log(response);
  });
};

module.exports = (event) => {
  const senderId = event.sender.id;
  const message = event.message.text;
  const apiaiSession = apiAiClient.textRequest(message, { sessionId: 'total-poc-bot' });
  apiaiSession.on('response', (response) => {
    const result = response.result.fulfillment.speech;
    sendTextMessage(senderId, result);
  });
  apiaiSession.on('error', error => console.log(error));
  apiaiSession.end();
};

Here is my node app

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const verificaton = require('./controllers/verification');
const messageWebhook = require('./controllers/messageWebhook');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(3000, () => console.log('Webhook server is listening, port 3000'));
app.get('/', verificaton);
app.post('/', messageWebhook);

Thanking in advance. looking forward for the replies.


Solution

  • The issue is resolved, i found out that facebook was blocked on my IP, so it was giving Error: socket hang up . I unblocked facebook and the api responded,

    Thanks