November 16, 2023 No Comments

In the modern digital era, WhatsApp has emerged as a favored communication platform for both businesses and customers. The WhatsApp Business API, once accessible to only a few, is now available to a wider array of businesses, opening up fresh avenues to deliver outstanding customer support and resolve user inquiries effectively.

A creative approach to Utilizing WhatsApp’s capabilities involves combining it with Amazon Lex, a robust natural language processing platform renowned for its Multilingual Support. This feature empowers you to construct chatbots capable of engaging users in multiple languages during a single conversation. Such versatility is instrumental in crafting personalized chatbots tailored to specific needs. This integration equips businesses to develop a WhatsApp chatbot that adeptly manages a diverse range of customer inquiries, making it a valuable asset for e-commerce and small businesses aiming to elevate their customer support services.

Real-World Example

Let’s dive into a real-world example to illustrate how this integration can revolutionize customer interactions:

Imagine you run an e-commerce store that sells a variety of electronic gadgets, and you’ve integrated the WhatsApp Business API with Amazon Lex to create a sophisticated chatbot.

A customer named Alex reached out on your e-commerce store’s WhatsApp business account, asking about the availability of the latest smartphone model. The Amazon Lex-powered chatbot efficiently provided details on availability, specifications, and pricing, even offering help with ordering.

However, Alex had specific queries about the smartphone’s camera features and compatibility with his existing accessories. These questions required a more detailed approach. The chatbot seamlessly handed over the conversation to a live human customer support agent available on WhatsApp. The agent took over from where the chatbot left off, addressing Alex’s concerns with expertise and a welcoming demeanor.

Key Benefits
  • The integration of WhatsApp Business API with Amazon Lex not only enables businesses to provide automated responses but also ensures a smooth transition to human agents when needed. This dynamic interaction enhances the customer experience, instilling confidence in your brand’s commitment to providing excellent service.
  • The combination of chatbot capabilities with the knowledge and skills of human agents allows businesses to efficiently and effectively address the diverse requirements of their customers. This degree of responsiveness and personalization serves as a distinguishing factor in the highly competitive realm of contemporary customer service.

As we explore the integration of WhatsApp Business API and Amazon Lex, we’ll delve deeper into the technical aspects of creating a chatbot with human handover, providing practical insights and steps to empower your business with this powerful tool.

Prerequisite Tutorials

Before you begin this tutorial, it’s essential to review the following prerequisite tutorials:

1. Explore a WhatsApp Business API: Click for Tutorial

2. Create a Chatbot using Amazon Lex: Click for Tutorial

These tutorials provide the foundational knowledge required for successfully implementing the integration discussed in this tutorial. 

Technical Implementation

Ensure you have followed the WhatsApp bot tutorial and Amazon Lex integration tutorial.  We retrieve user messages from the WhatsApp bot and transmit them to Amazon Lex. This process involves several key steps.

To integrate Amazon Web Services (AWS) capabilities into your Python scripts or applications, you can install the boto3 library using pip. Boto3 serves as the official AWS SDK for Python, enabling seamless interaction with a variety of AWS services. Simply use the following command to install it:

				
					pip install boto3
				
			

Step 1: Let’s get started by replacing the code with the one specified in Step 17 of the WhatsApp bot tutorial. This code will help you set up the integration seamlessly: 

				
					from flask import Flask, request
import requests
import os
import json
import boto3
import datetime
app = Flask(__name__)


# Credential Details
MOBILE_NUMBER = '<User_phonenumber>'
ADMIN_NUMBER = '<Admin_number>'


language_code="<en-US>"


# Connect with amazon Lex and send response to user
def send_chat_bot(msg,session_id_1):
   botId = "<Your_chatbot_id>"
   botAliasId = "<Your_chatbotAliasId>"
   localeId = "en_US"
   sessionId = session_id_1
   client=boto3.client('lexv2-runtime',region_name='us-east-1',aws_access_key_id='<Your_aws_access_key_id>',
   aws_secret_access_key='<Your_aws_secret_access_key>')


   response = client.recognize_text(
       botId=botId,
       botAliasId=botAliasId,
       localeId=localeId,
       sessionId=sessionId,
   text=msg)
   print(response)
   action = response['sessionState']['dialogAction']['type']
   intent = response['sessionState']['intent']['name']
   try:
       response_msg = response['messages'][0]['content']
   except:
       response_msg = "Connect With the user"
   print("Intent:",response['sessionState']['intent']['name'])
   print("Next Action:",response['sessionState']['dialogAction']['type'])
  
   return response_msg,action,intent


# connect with the admin and admin direct messages to user
def send_msg_admin(msg):
   headers = {
      'Authorization': f'Bearer {ACCESS_TOKEN}',
  }
   json_data = {
       'messaging_product': 'whatsapp',
       'to': ADMIN_NUMBER ,
       'type': 'text',
       "text": {
           "body": msg
       }
   }
   response=requests.post(f'https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages', headers=headers, json=json_data)
   return response.text


# store all details in json file
def writedata(human_phone,user_phone,human_interface):
   current_time = datetime.datetime.now()
   dict_data = {'human_phone': [human_phone], 'user_phone': [user_phone],       'human_interface':[human_interface], 'last_updated': [str(current_time)]}
   with open('data.json','w') as json_data:
     json.dump(dict_data,json_data)


#  bot connect with the user
def send_msg(msg,phonenumber):
   headers = {
      'Authorization': f'Bearer {ACCESS_TOKEN}',
  }
   json_data = {
       'messaging_product': 'whatsapp',
       'to': phonenumber,
       'type': 'text',
       "text": {
           "body": msg
       }
   }
   response=requests.post(f'https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages', headers=headers, json=json_data)
   return response.text


@app.route('/receive_msg', methods=['POST','GET'])
def webhook():
   res = request.get_json()
   print(res)
 
   try:
       ADMIN_NUMBER = "<Admin Number>"
       if res['entry'][0]['changes'][0]['value']['messages'][0]['id']:
           language_code="en"
           session_id = res['entry'][0]['changes'][0]['value']['messages'][0]['from']
          
           if res['entry'][0]['changes'][0]['value']['messages'][0]['from'] == ADMIN_NUMBER:
               msg = res['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
               print(msg)
               if str(msg).lower() == "bye":
                   human_interface = "False"                                                                                       writedata(ADMIN_NUMBER,MOBILE_NUMBER,human_interface)
                   msg = "Thank you for connecting with us. We appreciate your time and value your input. If you have any further questions or need assistance in the future, please don't hesitate to reach out. Have a wonderful day ahead!"
               send_msg(msg,MOBILE_NUMBER)
           else:
               human_phone = ADMIN_NUMBER
               user_phone = session_id
                          
               msg = res['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
               if not os.path.exists('data.json'):
                   human_interface = 'False'
                   writedata(human_phone,user_phone,human_interface)


               with open('data.json','r') as json_data:
                   filtered_rows = json.load(json_data)
              
               if filtered_rows['human_interface'][0] == 'False':
                   session_id_1 = f"session_id{session_id}"
                   response, action,intent = send_chat_bot(msg,session_id_1)
                   print("response",response)
                   if intent== "human_transfer" and action == "close": 
                       message = f"Request To connect With you and user number is {session_id}"
                       send_msg_admin(message)
                       print("Send to Admin msg")
                       human_interface = "True"
                       writedata(human_phone,user_phone,human_interface)
                   else:
                       human_interface = "False"
                       writedata(human_phone,user_phone,human_interface)
                       send_msg(response,session_id)
                      
               else:
                   send_msg_admin(msg)
                  
             
   except:
       pass
   return '200 OK HTTPS.'


if __name__ == '__main__':
   app.run()
				
			

Step 2: Input values for MOBILE_NUMBER and ADMIN_NUMBER, ensure that they are different. You can also replace “language_code” as per your requirements, but it should be set to “en” by default.

Step 3: Input the values of botId, AWS access key ID, and AWS secret access key you have created in the Amazon lex  Tutorial, to which you will need to add the provided code.

Now, let’s understand the key functions and their roles in the WhatsApp bot with Human handover using Amazon Lex script:

1. send_chat_bot
The function demonstrates how Amazon Lex sends a request and receives a response via WhatsApp.  It is used to create an AWS service client object that allows your Lex bot to interact with  AWS services. We get a response and send it to the user.

2. send_msg_admin
In this function, When a user wants to connect with a human,  this function sends a message to the admin number. The admin directly responds to the user’s request.

3. writedata
In this function, we store information about the admin number, user number, user’s last update time, and a human interface. Initially, we set the human interface as “false”.

4. send_msg
In this function, we establish a connection between the bot and the user, and subsequently, we send a response back to the user.

When a user chats with our WhatsApp bot, the bot interacts with the user and provides responses using the Amazon lex.

Here are user responses on the Flask app server:

In the Flask server terminal, we receive feedback on the sent, read, and delivered messages, allowing us to monitor the status and progress of our message transmissions. And also got messages sent from Amazon Lex.

When a user requests to speak with a human or a bot does not understand what the user wants, Amazon lex initiates the action and connects them with an admin. It is helpful when things get a bit confusing or unclear during the conversation.

Here is the conversation of the admin directly connecting with the user and responding to the user’s queries.

We also receive responses in the Flask app terminal from the admin during the conversation between the admin and the user. 

We can end the conversation with a closing message, like “bye”, or any custom message you’ve chosen to use for concluding the conversation with the admin.

We hope you’ve successfully crafted a WhatsApp Chatbot utilizing Amazon Lex and are enjoying its functionality.

Write a comment

Your email address will not be published. Required fields are marked *

Want to talk to an Expert Developer?

Our experts in Generative AI, Python Programming, and Chatbot Development can help you build innovative solutions and scale your business faster.