We all agree to a point that by now we not only have heard about ChatGPT but also got a hands-on experience with it and we Loved it! For those who haven’t got a chance to get in touch with ChatGPT here is a brief introduction: ChatGPT is a large language model trained by OpenAI, and it was designed to assist users by generating human-like text based on the given prompt. It can help with a wide range of tasks, such as answering questions, providing information, and engaging in conversations on a variety of topics.

On top of that ChatGPT has left us dumbstruck by generating incredible answers to almost anything, you throw a question and it will provide you with the correct answer that we were finding hard to write.

At Pragnakalp we believe in making things user-friendly, since ChatGPT is something that will ease our life by leaps and bounds, we thought of making it accessible at our fingertip. So we brainstormed and came up with the idea of using ChatGPT on WhatsApp!!

Yes, you read it right “ChatGPT on WhatsApp!” or what if we say ChatGPT on any of your preferable 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 user WhatsApp messages and utilize ChatGPT to respond to those messages in detail.

Step 1: Integrate WhatsApp Business API

To automate the messages with the Flask application, we must integrate the WhatsApp Business API. For that follow our blog WhatsApp Business API Setup to send and receive messages using a test phone number. Please ensure that you have followed the blog’s instructions before proceeding.

Step 2: ChatGPT API

We’re going to use ChatGPT API  to respond user’s messages. The detailed instructions for setting up and using ChatGPT are provided in this section.

Now OpenAI announced an official API for ChatGPT which is powered by gpt-3.5-turbo, OpenAI’s most advanced language model.

Prerequisites

Before we begin utilizing the official ChatGPT API, please make sure that you have installed OpenAI Python library in your system.

pip install openai

The following is a Python code snippet that demonstrates how to make an API request:

import openai

openai.api_key = '<YOUR OPENAI API KEY>'
query = "Who won the world series in 2020?"
completion = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                        {"role": "user", "content": query},
                    
                    ]
            )
print("User prompt ==>", query)
print("ChatGPT response ==>", completion['choices'][0]['message']['content'])

The following is the response that was received from the ChatGPT API:

Step 3: Integrate ChatGPT API with Flask Application

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

Now we need to modify the flask app that we have created in Step 1. Replace your existing code with the below code to get the user message’s response from ChatGPT.

from flask import Flask, request
import requests
import openai

openai.api_key = '<YOUR OPENAI API KEY>'

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/LATEST-API-VERSION/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']
            completion = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "user", "content": chat_gpt_input}]
            )
            response = completion['choices'][0]['message']['content']
            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 the ngrok on terminal: ngrok http 5000

Step 4: Test WhatsApp Chatbot

Now come back to the “Getting Started” page as shown in the below image and click on the “Send message” button.

For all events, including message send, message delivery, and message read, you will receive a response on your Flask app at the receive_msg endpoint. The ChatGPT response can be checked on the server terminal as well.

Here is the ChatGPT response on our server.

You can also check the conversion with ChatGPT on WhatsApp

We hope that you have successfully integrated the ChatGPT in WhatsApp and having fun in 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 blog post series where we have provided a tutorial on how to create a chatbot for different platforms. You can explore these blogs and learn how you can set different kinds of rich responses which can increase user engagement on your chatbot.

Telegram: Create Telegram Bot Using Python Tutorial With Examples

Facebook Messanger: Create Facebook Messenger Bot Using Python Tutorial With Examples

Slack: Create Slack Bot Using Python Tutorial With Examples

Discord: Create Discord Bot Using Python Tutorial With Examples

Dialogflow ES API: How To Integrate Dialogflow ES API To Add NLP Capabilities In Your Chatbot?

Dialogflow CX API: How to integrate Dialogflow CX API to add NLP capabilities in your Chatbot?

Dialogflow ES with Twilio: Setup Twilio Integration On Your Server To Connect Google Dialogflow ES

Categories: Chatbots Development ChatGPT Natural Language Processing NLP Python WhatsApp Bot

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*