You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Messenger Bot中添加上下文功能并实现历史消息收据(Node.js)

Hey there! Let's break down how to tackle your Messenger Bot needs step by step.

1. Fetching Earlier Conversation History

The Messenger Platform does provide an API to retrieve conversation history, but there are a few key constraints to keep in mind:

  • You can only access history related to your bot, and only if the user has interacted with your bot (sent messages, clicked buttons, etc.)
  • History is retained for a limited time (currently 90 days, always double-check Facebook's latest policies)
  • Your app needs the pages_messaging permission approved to use this endpoint

In Node.js, you can call the GET /v18.0/{page-id}/conversations/{conversation-id}/messages endpoint to pull historical messages. Here's a quick example:

const axios = require('axios');

async function getConversationHistory(pageId, conversationId, accessToken) {
  try {
    const response = await axios.get(`https://graph.facebook.com/v18.0/${pageId}/conversations/${conversationId}/messages`, {
      params: {
        access_token: accessToken,
        limit: 50, // Adjust based on how many messages you need to fetch
        fields: 'message,created_time,sender' // Fields you want to retrieve
      }
    });
    return response.data.data;
  } catch (error) {
    console.error('Failed to fetch history:', error.response.data);
    throw error;
  }
}

You can get the conversation-id from your webhook payload—look for thread_id or use the combination of sender.id and recipient.id from incoming messages.

2. Storing Data in Messenger's Built-in Tools

Absolutely! Using Messenger's native user notes or custom fields is compliant with Facebook's privacy policies (since data stays on their platform instead of third-party servers). Here are two solid options:

Option 1: User Notes

You can add a note to a user's profile to store short, structured data (like order summaries or selected items) that you can later pull to generate receipts. Here's how to implement it in Node.js:

// Update user note
async function setUserNote(userId, note, pageId, accessToken) {
  try {
    await axios.post(`https://graph.facebook.com/v18.0/${pageId}/user_notes`, {
      user_id: userId,
      note: note,
      access_token: accessToken
    });
    console.log('User note updated successfully');
  } catch (error) {
    console.error('Failed to update user note:', error.response.data);
    throw error;
  }
}

// Retrieve user note
async function getUserNote(userId, pageId, accessToken) {
  try {
    const response = await axios.get(`https://graph.facebook.com/v18.0/${userId}/user_notes`, {
      params: {
        access_token: accessToken,
        fields: 'note,created_time'
      }
    });
    return response.data.data[0]?.note || '';
  } catch (error) {
    console.error('Failed to fetch user note:', error.response.data);
    throw error;
  }
}

Notes have a character limit (around 1000), so store structured data as JSON strings (e.g., JSON.stringify({items: ["Coffee", "Bagel"], total: 8.50})) for easy parsing later.

Option 2: Custom User Fields

For more structured data, define custom user fields in your Facebook Developer Dashboard (under Messenger settings), then write and read data to them via API:

// Set custom user field
async function setCustomUserField(userId, fieldName, fieldValue, accessToken) {
  try {
    await axios.post(`https://graph.facebook.com/v18.0/${userId}`, {
      [fieldName]: fieldValue,
      access_token: accessToken
    });
    console.log('Custom field updated successfully');
  } catch (error) {
    console.error('Failed to update custom field:', error.response.data);
    throw error;
  }
}

// Retrieve custom user field
async function getCustomUserField(userId, fieldName, accessToken) {
  try {
    const response = await axios.get(`https://graph.facebook.com/v18.0/${userId}`, {
      params: {
        access_token: accessToken,
        fields: fieldName
      }
    });
    return response.data[fieldName];
  } catch (error) {
    console.error('Failed to fetch custom field:', error.response.data);
    throw error;
  }
}
3. End-to-End Flow for Generating Receipts

Here's a simple workflow to tie it all together:

  • When a user sends a message, receive it via your webhook, then fetch the relevant conversation history using the API above
  • Extract key details (like items selected, amounts) and store them as a JSON string in a user note or custom field
  • When the user requests a receipt, retrieve the stored data, parse it, format it into a clear receipt message, and send it back to the user
Key Privacy & Implementation Notes
  • Stick to privacy rules: Only store data that's necessary for generating receipts, and make sure users are aware you're storing this information (per Facebook's policies)
  • Permission checks: Ensure your bot has the approved pages_messaging permission—without it, you won't be able to access history or user data endpoints
  • Error handling: Always add robust error handling for API calls (e.g., rate limits, permission errors) to keep your bot stable

内容的提问来源于stack exchange,提问作者Mohsin Hayat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:08:43