Build an automated, AI-powered Facebook Messenger Chatbot with ChatGPT using Flask

This blog shows how to use Facebook Messenger Chatbot, Flask and ChatGPT together to deliver text messages with detailed responses.

Step 1: Create a Facebook Chatbot

We need to create a Facebook Messenger Chatbot to automate messaging with ChatGPT. Please follow the steps step 1 to step 8 in our blog post on Facebook Messenger Bot. Make sure you’ve followed the instructions on the blog before continuing.

Step 2: ChatGPT API

You can check our blog WhatsApp Chatbot With ChatGPT Step 2 “ChatGPT API” which has instructions on how to set up and use ChatGPT.

Step 3: Integrate the ChatGPT API with the Flask application

It’s time to integrate our ChatGPT API with the Flask app now that it’s successfully installed.

However, the ChatGPT API will continue to run in the background of the Firefox browser, which may interfere with receiving responses from the ChatGPT API, so we need to end the process that is currently running in the browser.

def process():
    try:
         
        # iterating through each instance of the process
        for line in os.popen("ps ax | grep firefox | grep -v grep"):
            fields = line.split()
             
            # extracting Process ID from the output
            pid = fields[0]
             
            # terminating process
            os.kill(int(pid), signal.SIGKILL)
        print("Process Successfully terminated")
         
    except:
        print("Error Encountered while running script")

The Flask application we created step 1 must be changed now. To get a ChatGPT response to user messages, replace the existing code in your Flask application with the following code.

import requests
import os, signal
from flask import Flask, request
from chatgpt_wrapper import ChatGPT

app = Flask(__name__)
 
# This is page access token that you get from facebook developer console.
PAGE_ACCESS_TOKEN = '<Your PAGE ACCESS TOKEN>'
# This is API key for facebook messenger.
API="https://graph.facebook.com/LATEST-API-VERSION/me/messages?access_token="+PAGE_ACCESS_TOKEN

def process():
     
    try:
         
        # iterating through each instance of the process
        for line in os.popen("ps ax | grep firefox | grep -v grep"):
            fields = line.split()
             
            # extracting Process ID from the output
            pid = fields[0]
             
            # terminating process
            os.kill(int(pid), signal.SIGKILL)
        # print("Process Successfully terminated")
         
    except:
        print("Error Encountered while running script"

@app.route("/", methods=['POST'])
def fbwebhook():
    data = request.get_json()
    try:
        if data['entry'][0]['messaging'][0]['sender']['id']:
            message = data['entry'][0]['messaging'][0]['message']
            sender_id = data['entry'][0]['messaging'][0]['sender']['id']
            chat_gpt_input=message['text']
            print(chat_gpt_input)
            bot = ChatGPT()
            chatbot_res = bot.ask(chat_gpt_input) 
            print("ChatGPT Response=>",chatbot_res)
            process()
            return chatbot_res
    except Exception as e:
        print(e)
        pass
    return '200 OK HTTPS.'
if __name__ =='__main__':
    app.run()

Note:

Run the flask application in the terminal. python SCRIPT_NAME.py
Run ngrok in terminal. ngrok http 5000

Step 4: Test Facebook Messenger Chatbot:

If you visit your Facebook page, you will be able to test the bot by sending a message. If you have configured everything correctly, you should receive a message from your page.

After sending a message to the bot, you will receive a reply from ChatGPT on the server as shown below

When the user sends a message, the generated page successfully sends them a ChatGPT response.

Let us know if you have any problems configuring or using the script. We will be happy to help. Contact us or write your request in the comments.

Also, check out our other tutorials to learn how to build a ChatGPT chatbot on different platforms.

WhatsApp with ChatGPT. Build an automated, AI-powered WhatsApp Chatbot with ChatGPT using Flask

Telegram Bot with ChatGPT. Build an automated, AI-powered Telegram Chatbot with ChatGPT using Flask.

Slack Chatbot with ChatGPT. Build an automated, AI-powered Slack Chatbot with ChatGPT using Flask.

We have already created a series of blog posts where we provided a tutorial on how to create a chatbot for different platforms. You can explore these blogs and learn how you can define different types of rich responses that can increase user engagement in your chatbot.

Telegram: Create a Telegram bot using Python tutorial with examples

Facebook Messenger. Create a Facebook Messenger bot using Python tutorial with examples

Slack: Create a Slack Bot using Python tutorial with examples

Discord: Create a Discord bot using Python tutorial with examples



Source link