Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Create a Telegram Bot using Python
Next article icon

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.

System Requirements:

Getting Started

Step 1:Set up the Twilio account using theTwilio WhatsApp API.

Go to this link and click onsignup and start buildingbutton and fill in your details and verify your email ID and mobile number.

Sign up

After login, select theDevelop option from the left menu and then further select theMessaging subject then select the Try it out option, and in the last click onSend 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 secret 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

Creating a Flask Chatbot Service for running the bot locally:

Step 1: Import the necessary files needed to run this flask app.

Python3
fromflaskimportFlask,requestimportrequestsfromtwilio.twiml.messaging_responseimportMessagingResponse

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
fromflaskimportrequestincoming_msg=request.values.get('Body','').lower()

To send messages/respond to the user, we are going to useMessagingResponse() function from Twilio.

Python3
fromtwilio.twiml.messaging_responseimportMessagingResponseresponse=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 fromgeeksforgeeks to the user.

Python3
# chatbot logicdefbot():# user inputuser_msg=request.values.get('Body','').lower()# creating object of MessagingResponseresponse=MessagingResponse()# User Queryq=user_msg+"geeksforgeeks.org"# list to store urlsresult=[]# searching and storing urlsforiinsearch(q,tld='co.in',num=6,stop=6,pause=2):result.append(i)# displaying resultmsg=response.message(f"--- Results for '{user_msg}' ---")forresultinsearch_results:msg=response.message(result)returnstr(response)

Here, in this function, usinguser_msg will receive the user response/query. Then we are usinggooglesearch to fetch the first  5 links from the Google search with the user query and storing them into a list calledresult. 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

Below is the full implementation:

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
fromflaskimportFlaskfromgooglesearchimportsearchimportrequestsfromtwilio.twiml.messaging_responseimportMessagingResponseapp=Flask(__name__)@app.route("/",methods=["POST"])# chatbot logicdefbot():# user inputuser_msg=request.values.get('Body','').lower()# creating object of MessagingResponseresponse=MessagingResponse()# User Queryq=user_msg+"geeksforgeeks.org"# list to store urlsresult=[]# searching and storing urlsforiinsearch(q,num_results=3):result.append(i)# displaying resultmsg=response.message(f"--- Results for '{user_msg}' ---")forresultinsearch_results:msg=response.message(result)returnstr(response)if__name__=="__main__":app.run()

Output:


Building WhatsApp bot on Python
Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp