Facebook-OpenAI Knowledge Base Chatbot
Published: 2024-07-04 20:23:30


This project is a Node.js REST API that integrates OpenAI's GPT-4 with Facebook Messenger to create a knowledge-based chatbot. The chatbot uses predefined knowledge embedded in the prompt to respond to user messages on Facebook.

## Installation

1. **Initialize the project**:

    ```bash
    npm init -y
    ```

2. **Install required packages**:

    ```bash
    npm install express axios body-parser dotenv
    ```

## Environment Variables

Create a `.env` file in the root of your project and add the following environment variables:

```plaintext
FACEBOOK_PAGE_ID=your_page_id
FACEBOOK_APP_ID=your_app_id
FACEBOOK_APP_SECRET=your_app_secret
FACEBOOK_VERIFY_TOKEN=your_verify_token
OPENAI_API_KEY=your_openai_api_key
```

Replace `your_page_id`, `your_app_id`, `your_app_secret`, `your_verify_token`, and `your_openai_api_key` with your actual credentials.

## Usage

1. **Create the main server file `index.js`**:

    ```javascript
    const express = require('express');
    const bodyParser = require('body-parser');
    const axios = require('axios');
    require('dotenv').config();

    const app = express();
    app.use(bodyParser.json());

    const { FACEBOOK_PAGE_ID, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, FACEBOOK_VERIFY_TOKEN, OPENAI_API_KEY } = process.env;

    // Define your predefined knowledge base
    const knowledgeBase = `
    You are a chatbot with the following predefined knowledge:
    1. The capital of France is Paris.
    2. The Python programming language was created by Guido van Rossum and first released in 1991.
    3. The tallest mountain in the world is Mount Everest, standing at 8,848 meters (29,029 feet).
    4. The theory of relativity was developed by Albert Einstein.
    5. The Great Wall of China is over 13,000 miles long.

    Answer questions based on this knowledge.
    `;

    // Endpoint for Facebook to verify the webhook
    app.get('/webhook', (req, res) => {
        const mode = req.query['hub.mode'];
        const token = req.query['hub.verify_token'];
        const challenge = req.query['hub.challenge'];

        if (mode && token) {
            if (mode === 'subscribe' && token === FACEBOOK_VERIFY_TOKEN) {
                console.log('WEBHOOK_VERIFIED');
                res.status(200).send(challenge);
            } else {
                res.sendStatus(403);
            }
        }
    });

    // Endpoint to handle messages
    app.post('/webhook', async (req, res) => {
        const body = req.body;

        if (body.object === 'page') {
            body.entry.forEach(async entry => {
                const webhookEvent = entry.messaging[0];
                const senderId = webhookEvent.sender.id;
                const messageText = webhookEvent.message.text;

                // Process the message with OpenAI
                try {
                    const openaiResponse = await axios.post('https://api.openai.com/v1/completions', {
                        model: 'text-davinci-003',
                        prompt: `${knowledgeBase}\n\nUser: ${messageText}\nChatbot:`,
                        max_tokens: 150,
                        stop: ['User:', 'Chatbot:']
                    }, {
                        headers: {
                            'Authorization': `Bearer ${OPENAI_API_KEY}`
                        }
                    });

                    const openaiMessage = openaiResponse.data.choices[0].text.trim();

                    // Send response back to Facebook Messenger
                    await axios.post(`https://graph.facebook.com/v11.0/me/messages?access_token=${FACEBOOK_APP_ID}|${FACEBOOK_APP_SECRET}`, {
                        recipient: {
                            id: senderId
                        },
                        message: {
                            text: openaiMessage
                        }
                    });

                    res.status(200).send('EVENT_RECEIVED');
                } catch (error) {
                    console.error('Error processing message:', error);
                    res.sendStatus(500);
                }
            });
        } else {
            res.sendStatus(404);
        }
    });

    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    ```

## Code Explanation

- **Webhook Verification**: Facebook sends a GET request to verify the webhook. The API responds with a challenge token to confirm the webhook.

- **Message Handling**: When a user sends a message to your Facebook page:
  - The API receives a POST request.
  - It extracts the message and sender ID.
  - It sends the message to OpenAI's GPT-4 model to generate a response using the predefined knowledge base.
  - It sends the generated response back to the user on Facebook Messenger.

## Run the Server

To start the server, run:

```bash
node index.js
```