Building WhatsApp bot on Python - GeeksforGeeks

31 Aug, 2021
A WhatsApp bot is application software that is able to carry on communication with humans in a spoken or written manner. And today we are going to learn how we can create a WhatsApp bot using python. First, let’s see the requirements for building the WhatsApp bot using python language.
A Twilio account and a smartphone with an active phone number and WhatsApp installed.
Must have Python 3.9 or newer installed in the system.
Flask: We will be using a flask to create a web application that responds to incoming WhatsApp messages with it.
ngrok: Ngrok will help us to connect the Flask application running on your system to a public URL that Twilio can connect to. This is necessary for the development version of the chatbot because your computer is likely behind a router or firewall, so it isn’t directly reachable on the Internet.
Step 1: Set up the Twilio account using the Twilio WhatsApp API.
Go to this link and click on signup and start building button and fill in your details and verify your email ID and mobile number.
Sign up
After login, select the Develop option from the left menu and then further select the Messaging subject then select the Try it out option, and in the last click on Send a WhatsApp message. This will open up a new webpage for setting up the WhatsApp Sandbox.
Setup Whatsapp messaging
Step 2: Configure the Twilio WhatsApp Sandbox by sending a message to this WhatsApp number with the secrete unique security code as shown in the below images:
Send the code as below format to the following number: +14155238886
secret code : join <secret-code>
Setup Sandbox
Now, send the secret code to the above WhatsApp message and you will receive a confirmation message as below:
Confirmation message
Step 3: Open up the terminal and run the following command to create a directory for the bot, to create a virtual environment for python, to install all the necessary packages.
To create  the directory and navigate to that directory:
mkdir geeks-bot && cd geeks-bot
To create and activate the python virtual environment:
python3 -m venv geek-bot-env && source geek-bot-env/bin/activate
To install Twilio, flask and requests: 
pip3 install twilio flask requests
Here are the above commands in just one line :
mkdir geek-bot && cd geek-bot && python3 -m venv geek-bot-env && source geek-bot-env/bin/activate && pip3 install twilio flask requests
Output:
Setting up folder structure
Step 1: Import the necessary files needed to run this flask app.
Python3
from flask import Flask, requestimport requestsfrom twilio.twiml.messaging_response import MessagingResponse
Step 2: Receiving message entered by the user and sending the response. We can access the user response that is coming in the payload of the POST request with a key of ’Body’.
Python3
from flask import request  incoming_msg = request.values.get('Body', '').lower()
To send messages/respond to the user, we are going to use MessagingResponse() function from Twilio.
Python3
from twilio.twiml.messaging_response import MessagingResponse  response = MessagingResponse()msg = response.message()msg.body('this is the response/reply  from the bot.)
Step 3: So now we will build the chatbot logic, we are going to ask the user to enter a topic that he/she want to learn then we send the message to the bot, and the bot will search the query and respond with the most relevant article from geeksfogeeks to the user.
Python3
# chatbot logicdef bot():      # user input    user_msg = request.values.get('Body', '').lower()      # creating object of MessagingResponse    response = MessagingResponse()      # User Query    q = user_msg + "geeksforgeeks.org"      # list to store urls    result = []      # searching and storing urls    for i in search(q, tld='co.in', num=6, stop=6, pause=2):        result.append(i)      # displaying result    msg = response.message(f"--- Result for '{user_msg}' are  ---")      msg = response.message(result[0])    msg = response.message(result[1])    msg = response.message(result[2])    msg = response.message(result[3])    msg = response.message(result[4])      return str(response)
Here, in this function, using user_msg will receive the user response/query. Then we are using google search to fetch the first  5 links from the Google search with the user query and storing them into a list called result. After that, are simply sending the first 5 links to the user using the Twilio messaging service.
To run the bot will follow these steps:
Firstly, run the above script using the following command:
python3 main2.py
Output:
Running the bot script
Secondly, open up another terminal window and run the following command to start the ngrok server.
ngrok http 5000
Output:
And third and last step we have to do is to set up the forwarding URL in the WhatsApp Sandbox Settings. Navigate to the following link and paste the forwarding URL in the selected location and click on save.
Link: https://www.twilio.com/console/sms/whatsapp/sandbox
Setup URL in Twilio
Here, we have imported all the necessary libraries that we’re going to use during the execution of the chatbot then we are creating a function called a bot, where we are going to implement our chatbot logic. In the bot function, firstly, we are fetching the response made by the user using WhatsApp and saving it into a variable called user_msg. After that we have created an object of MessagingResponse(), we need that for sending the reply to the user using WhatsApp. We are appending user query with the word “geeksforgeeks.org” because we have made this bot with respect to a user who might have the study-related queries and he/she can ask any doubt related to studies. After that, we have created a list called result where we are going to save the URLs that we have to send to the user. We are using the google search library for googling purposes. Using for loop, we are fetching the first 5 article links and saving them into the result. Using response.message() function we are simply sending the result back to the user through WhatsApp.
Python3
from flask import Flaskfrom googlesearch import searchimport requestsfrom twilio.twiml.messaging_response import MessagingResponse    app = Flask(__name__)  @app.route("/", methods=["POST"])  # chatbot logicdef bot():      # user input    user_msg = request.values.get('Body', '').lower()      # creating object of MessagingResponse    response = MessagingResponse()      # User Query    q = user_msg + "geeksforgeeks.org"      # list to store urls    result = []      # searching and storing urls    for i in search(q, tld='co.in', num=6, stop=6, pause=2):        result.append(i)      # displaying result    msg = response.message(f"--- Result for '{user_msg}' are  ---")      msg = response.message(result[0])    msg = response.message(result[1])    msg = response.message(result[2])    msg = response.message(result[3])    msg = response.message(result[4])      return str(response)    if __name__ == "__main__":    app.run()
Output:
Picked
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list