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

We all agree on one point that by now we have not only heard about ChatGPT but also got hands-on experience with it and we liked it. For those who have not had a chance to interact with ChatGPT, here is a brief introduction. ChatGPT is a broad language model trained by OpenAI and designed to help users generate human-like text based on a given prompt. It can help with a variety of tasks, such as answering questions, providing information, and conducting conversations on a variety of topics.

Also, ChatGPT has fooled us by creating incredible answers for almost anything, you ask a question and it will give you the right answer that we struggled to write.

At Pragnakalp, we believe in making things user-friendly, since ChatGPT is something that will ease our lives by leaps and bounds, we thought of making it available at our fingertips. So we thought and came up with the idea to use ChatGPT on WhatsApp!!

Yes, you read that right “ChatGPT on WhatsApp”. or what if we say ChatGPT on any of your preferred platforms?

This blog describes how you can integrate the WhatsApp Business API hosted by Meta and create a python application based on the Flask web framework that can receive users’ WhatsApp messages and use ChatGPT to respond to those messages in detail for:

Step 1: Integrate the WhatsApp Business API

To automate messaging with the Flask app, we need to integrate the WhatsApp Business API. For that follow our blog WhatsApp Business API Setup to send and receive messages with a test phone number. Please make sure you have followed the instructions on the blog before continuing.

Step 2: ChatGPT API

We are going to use the ChatGPT API to reply to user messages. Detailed instructions for setting up and using ChatGPT are provided in this section.

The ChatGPT API offers an easy way to incorporate technology-advanced language understanding into your web services. Since there are currently no official API endpoints, the ChatGPT community has developed a number of simple solutions that you can use.

Prerequisites:

Before we start using the unofficial ChatGPT API, please follow the steps listed below to configure the code.

1. Clone this Git repository.

git clone https://github.com/mmabrouk/chatgpt-wrapper

2. To use this API, make sure you have setuptools installed

pip install setuptools

3. Install dependencies by running below command.

pip install git+https://github.com/mmabrouk/chatgpt-wrapper

4. Browser installation of Playwright is required to run the application. By default, the script will use Firefox.

playwright install firefox

After running the above command it will give a message as shown in the below image if you are installing dramatist for the first time it will ask you to run playwright install order only once.

5. After completing the installation, you can run the program in Install mode by running the below command

chatgpt install

It will open a new browser window as shown in the image below and ask you to login or register at chat.openai.com.

Log in and stop the running program and restart it.

Now you can use it with a shell command chatgpt <your prompt> without “Install” as shown in the image below

Note:However, after some time, if you are not actively using ChatGPT, it will automatically expire your session and you will need to log in again chatgpt install

Create an instance of the class, use the request method to send a message to OpenAI, and then use the response to interact with ChatGPT via the ChatGPT class as an API.

from chatgpt_wrapper import ChatGPT
import time

prompt = "what is coronavirus? explain me in 2 3 lines"
bot = ChatGPT()
response = bot.ask(prompt)
print("Prompt: ",prompt)
print("Response: ",response)

This is the response we got from the chatGPT API.

Step 3: Integrate the ChatGPT API with the Flask application

After our ChatGPT API is successfully installed, it’s time to integrate it with the flask application.

Now we need to modify the flask application we created in Step 1. Replace your existing code with the code below to get a user message reply from ChatGPT.

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


app = Flask(__name__)
 
def send_msg(msg,receiver_number):

   headers = {
       'Authorization': 'Bearer VERIFICATION_TOKEN',
   }
   json_data = {
       'messaging_product': 'whatsapp',
       'to': receiver_number,
       'type': 'text',
       "text": {
           "body": msg
       }
   }
   response = requests.post('https://graph.facebook.com/v13.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
   print(response.text)
 

@app.route('/receive_msg', methods=['POST','GET'])
def webhook():
   res = request.get_json()
   print(res)
   try:
       if res['entry'][0]['changes'][0]['value']['messages'][0]['id']:
           chat_gpt_input=res['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
           bot = ChatGPT()
           response = bot.ask(chat_gpt_input) 
           print("ChatGPT Response=>",response)
           receiver_number=res['entry'][0]['changes'][0]['value']['contacts'][0]['wa_id']
           send_msg(response,receiver_number)
   except:
       pass
   return '200 OK HTTPS.'
 
  
if __name__ == "__main__":
   app.run(debug=True)

Note:

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

Step 4: Test WhatsApp Chatbot:

Now go back to the Start page as shown in the image below and click the Send Message button.

For all events, including message sending, message delivery, and message reading, you will receive a response in your Flask application on the receive_msg endpoint. The ChatGPT response can also be checked on the server terminal.

Here is the response from ChatGPT on our server.

You can also check the conversion via ChatGPT on WhatsApp

We hope you have successfully integrated ChatGPT in WhatsApp and had fun using it.

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

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

Facebook Messenger with ChatGPT. Build an automated, AI-powered Facebook Messenger 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