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

如何获取Messenger聊天机器人历史消息并实现上下文记忆?

How to Add Context Memory to Your Messenger News Bot

Great question—handling conversation context is what turns a basic bot into a useful, natural-feeling one. For your news bot scenario, here’s exactly how to track the user’s last request and respond appropriately when they say "Yes":

1. Use Messenger's User Identifier (PSID) to Track Sessions

Every user interacting with your bot gets a Page Scoped ID (PSID)—this unique ID is included in every webhook event sent by Messenger when the user sends a message. You’ll use this ID to link all of a user’s messages to their conversation history.

2. Store Conversation Context in Your Backend

Messenger doesn’t persist conversation context for you, so you’ll need to save key details (like the user’s news topic and current conversation state) in a database. Here’s the breakdown:

What to Store

For your news bot, you’ll want to save per-user:

  • The last news topic they requested (e.g., "donald trump")
  • The current conversation state (e.g., "waiting_for_more_news"—so you know the user’s "Yes" refers to wanting more of that topic)

Example Implementation with Redis (Fast Key-Value Storage)

Redis is perfect for this since it’s fast for key-value storage and lets you set expiration times for old contexts. Here’s a simplified Node.js example:

const redis = require('redis');
const client = redis.createClient();

// Helper to send messages via Messenger API
function sendMessage(psid, text) {
  // Implement your Messenger send API call here (using the official SDK)
}

// Helper to fetch initial news for a topic
function fetchNews(topic) {
  // Call your news API to retrieve 3 articles
}

// Helper to fetch additional news for a topic
function fetchMoreNews(topic) {
  // Call your news API to retrieve 3 more articles
}

// Process incoming webhook events from Messenger
app.post('/webhook', (req, res) => {
  req.body.entry.forEach(entry => {
    entry.messaging.forEach(event => {
      const psid = event.sender.id;
      const userMessage = event.message.text.toLowerCase();

      // Check if we have existing context for this user
      client.get(`user:${psid}:context`, (err, rawContext) => {
        if (err) throw err;
        const context = rawContext ? JSON.parse(rawContext) : null;

        // Case 1: User is responding to "Would you like more?"
        if (context && context.state === 'waiting_for_more_news' && 
            (userMessage === 'yes' || userMessage === 'sure' || userMessage === 'give me more')) {
          fetchMoreNews(context.topic)
            .then(news => {
              sendMessage(psid, `Here's 3 more articles about ${context.topic}! ... Would you like more?`);
              // Update context to keep the state alive
              client.set(`user:${psid}:context`, JSON.stringify({
                topic: context.topic,
                state: 'waiting_for_more_news'
              }));
              // Set a 1-hour expiration to avoid stale context
              client.expire(`user:${psid}:context`, 3600);
            });
        } 
        // Case 2: User is making a new news request
        else if (userMessage.includes('show me news about')) {
          const topic = userMessage.replace('show me news about', '').trim();
          fetchNews(topic)
            .then(news => {
              sendMessage(psid, `Here's 3 articles about ${topic}! ... Would you like more?`);
              // Save context for future responses
              client.set(`user:${psid}:context`, JSON.stringify({
                topic: topic,
                state: 'waiting_for_more_news'
              }));
              client.expire(`user:${psid}:context`, 3600);
            });
        } 
        // Case 3: Unrecognized message
        else {
          sendMessage(psid, "Sorry, I didn't catch that. Try asking for news like 'Show me news about donald trump'!");
        }
      });
    });
  });
  res.status(200).send('EVENT_RECEIVED');
});

3. Enhance with NLP for Flexible Responses

If users might reply with variations like "Absolutely" or "Keep going", add a lightweight NLP tool (like Dialogflow or a simple regex-based intent matcher) to recognize the "want more news" intent. Combine this with your stored context to confirm which topic they’re referring to.

4. Optional: Fetch Historical Messages via Messenger API

If you ever need to retrieve past messages directly from Messenger (instead of storing your own), use the GET /me/messages endpoint with the user’s PSID. Note that this has rate limits and only returns recent messages, so storing your own context is still the more reliable approach for most cases.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:18:41