nattik
nattik

Reputation: 27

Facebook Messenger Webhook Not Tracking Some Instagram Messages

I have set up a Facebook Messenger webhook to log all incoming and outgoing messages into a Google Sheet. My webhook is successfully receiving messages from my Facebook page and some Instagram accounts, but some Instagram messages are skipped. My account when DMing works and logs fine, but other accounts are not recorded. I do not have this issue with Facebook messages. (app is not in development mode)

Here’s What I’ve Configured:

1.  App Permissions:

My app has the following permissions: • pages_messaging • pages_manage_metadata 2. Webhooks: The webhook is subscribed to: • messages • message_echoes 3. Instagram Account: My Instagram Business account is linked to the Facebook Page, and the Manage Messaging toggle is turned ON.

Issue:

Code I’m Using:

Here’s the current Cloud Function code (Node.js 20) that processes webhook events and appends them to a Google Sheet:

const { google } = require("googleapis");
const VERIFY_TOKEN = "your_secure_token"; // Replace with your secure token
const SHEET_ID = "your_google_sheet_id"; // Your Google Sheet ID
const TAB_NAME = "Facebook Messenger"; // Your Google Sheet tab name
const CREDENTIALS = require("./credentials.json");

// Google Sheets API: Append data function
async function appendToSheet(data) {
  const auth = new google.auth.GoogleAuth({
    credentials: CREDENTIALS,
    scopes: ["https://www.googleapis.com/auth/spreadsheets"],
  });

  const sheets = google.sheets({ version: "v4", auth });
  await sheets.spreadsheets.values.append({
    spreadsheetId: SHEET_ID,
    range: `${TAB_NAME}!A1`,
    valueInputOption: "USER_ENTERED",
    resource: { values: [data] },
  });
}

// Helper function to determine platform
function getPlatform(id) {
  return id.startsWith("178") ? "Instagram" : "Facebook";
}

// Exported webhook function for Cloud Functions
exports.fbWebhook = async (req, res) => {
  if (req.method === "GET") {
    const mode = req.query["hub.mode"];
    const token = req.query["hub.verify_token"];
    const challenge = req.query["hub.challenge"];

    if (mode === "subscribe" && token === VERIFY_TOKEN) {
      return res.status(200).send(challenge);
    } else {
      return res.status(403).send("Verification failed");
    }
  }

  if (req.method === "POST") {
    try {
      console.log("Full Payload Received:", JSON.stringify(req.body, null, 2));
      const entry = req.body.entry || [];

      for (const event of entry) {
        const messaging = event.messaging || [];
        const platform = getPlatform(event.id); // Determine platform

        for (const msg of messaging) {
          let row = [];

          // Handle incoming messages
          if (msg.message && !msg.message.is_echo && msg.sender?.id) {
            row = [
              new Date().toISOString(),
              "incoming_message",
              msg.sender.id,
              msg.message.text || "Non-text message",
              platform,
            ];
          }

          // Handle outgoing messages (message_echoes)
          if (msg.message?.is_echo && msg.recipient?.id) {
            row = [
              new Date().toISOString(),
              "outgoing_message",
              msg.recipient.id,
              msg.message.text || "Non-text message",
              platform,
            ];
          }

          // Append row to Google Sheet
          if (row.length > 0) {
            await appendToSheet(row);
          }
        }
      }
      res.status(200).send("EVENT_RECEIVED");
    } catch (err) {
      console.error("Error handling webhook:", err.message);
      res.sendStatus(500);
    }
  } else {
    res.set("Allow", "GET, POST").status(405).send("Method Not Allowed");
  }
};

Has anyone experienced this problem before?

Upvotes: -1

Views: 35

Answers (0)

Related Questions