Building WhatsApp bot on Python

Last Updated : 20 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  • 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.

Getting Started

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 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




from flask import Flask, request
import requests
from 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 geeksforgeeks to the user.

Python3




# chatbot logic
def 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"--- Results for '{user_msg}' ---")
    for result in search_results:
        msg = response.message(result)
 
    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

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




from flask import Flask
from googlesearch import search
import requests
from twilio.twiml.messaging_response import MessagingResponse
 
 
app = Flask(__name__)
 
@app.route("/", methods=["POST"])
 
# chatbot logic
def 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, num_results=3):
        result.append(i)
 
    # displaying result
    msg = response.message(f"--- Results for '{user_msg}' ---")
    for result in search_results:
        msg = response.message(result)
 
    return str(response)
 
 
if __name__ == "__main__":
    app.run()


Output:



Previous Article
Next Article

Similar Reads

Chat Bot in Python with ChatterBot Module
Nobody likes to be alone always, but sometimes loneliness could be a better medicine to hunch the thirst for a peaceful environment. Even during such lonely quarantines, we may ignore humans but not humanoids. Yes, if you have guessed this article for a chatbot, then you have cracked it right. We won't require 6000 lines of code to create a chatbot
3 min read
Python - Making a Reddit bot with PRAW
Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them. A Reddit bot is something that automatically responds to a user’s post or automatically posts things at certain intervals. This could depend on what cont
2 min read
Instagram Bot using Python and InstaPy
In this article, we will design a simple fun project “Instagram Bot” using Python and InstaPy. As beginners want to do some extra and learning small projects so that it will help in building big future projects. Now, this is the time to learn some new projects and a better future. This python project gives the functionality of Instagram bot to like
3 min read
How to Build a Simple Auto-Login Bot with Python
In this article, we are going to see how to built a simple auto-login bot using python. In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come out of this problem lets, built our own auto logi
3 min read
How to Build Web scraping bot in Python
In this article, we are going to see how to build a web scraping bot in Python. Web Scraping is a process of extracting data from websites. A Bot is a piece of code that will automate our task. Therefore, A web scraping bot is a program that will automatically scrape a website for data, based on our requirements. Module neededbs4: Beautiful Soup(bs
8 min read
Create a Telegram Bot using Python
In this article, we are going to see how to create a telegram bot using Python. In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filt
6 min read
How to Make an Instagram Bot With Python and InstaBot?
In this article, we are going to see how to make an Instagram bot using Python and InstaBot. Bots are really common these days to send messages, upload photos, send wishes, and many more things. Bots reduce our work, save time. Today we are creating an Instagram bot that can do the following things. Functions performed by the botFollow one or more
4 min read
Automated SSH bot in Python
In this article, we are going to see how we can use Python to Automate some basic SSH processes. What is SSH? SSH stands for Secure Shell or Secure Socket Shell, in simple terms, it is a network communication protocol used to communicate between two computers and share data among them. The main feature of SSH is that the communication between two c
8 min read
Keyboard buttons in Telegram bot Using Python
One common way that we interact with the Telegram bot is through the use of keyboard buttons. These buttons give a convenient and intuitive way to input data and perform specific actions within the bot. Without keyboard buttons, we would have to manually type in commands or responses, which could be time-consuming and may lead to errors. Keyboard b
9 min read
Make an Instagram Bot With Python
Instagram is a powerful social media tool that you can use for marketing or networking. However, to successfully do any of that you need to have a good heavy follower base. You can't simply share a post with 50 followers and call it successful marketing. No matter what your goals are, having a large followers list is what everyone wishes for. If yo
6 min read
Create a Web-Crawler Notification Bot in Python
In this article, we will guide you through the process of creating a Web-Crawler Notification Bot using Python. This notification bot is designed to display notification messages on your window, providing a useful tool for alerting users to relevant information gathered through web crawling. What is a Notification Bot?A Notification Bot is a progra
3 min read
E-Mails Notification Bot With Python
Email continues to be a widely used communication method, making it an effective platform for receiving updates and staying connected. However, manual email notifications for recurring events or tasks can be inefficient and time-consuming. Python offers a robust toolset to develop automated email notification bots, enabling seamless and efficient c
3 min read
Creating a Discord Bot in Python
If you are familiar with online communities and if you are a part of one or you own one, you must have heard about discord and in discord, you may have seen bots managing those communities. So in this article, we are going to set up our discord developer portal account and will create a discord bot. A minimal bot with basic functionalities and if y
10 min read
Spam bot using PyAutoGUI
PyAutoGUI is a Python module that helps us automate the key presses and mouse clicks programmatically. In this article we will learn to develop a spam bot using PyAutoGUI. Spamming - Refers to sending unsolicited messages to large number of systems over the internet. This mini-project can be used for many real-life applications like: Remind your fr
2 min read
Converting WhatsApp chat data into a Word Cloud using Python
Let us see how to create a word cloud using a WhatsApp chat file. Convert the WhatsApp chat file from .txt format to .csv file. This can be done using Pandas. Create a DataFrame which read the .txt file. The .txt file had no columns like it is in an .csv file. Then, split the data into columns by separating them and giving each column a name. The f
4 min read
Export WhatsApp Chat History to Excel Using Python
In this article, we will discuss how to export a specific user's chats to an Excel sheet. To export the chats, we will use several Python modules and libraries. In the Excel file, we will create four columns: Date, Time, Name, and Message. We'll create these columns through Pandas, export all the chat details to their respective columns, and use Pu
5 min read
Share WhatsApp Web without Scanning QR code using Python
Prerequisite: Selenium, Browser Automation Using Selenium In this article, we are going to see how to share your Web-WhatsApp with anyone over the Internet without Scanning a QR code. Web-Whatsapp store sessions Web Whatsapp stores sessions in IndexedDB with the name wawc and syncs those key-value pairs to local storage. IndexedDB stores the data i
5 min read
Automate WhatsApp Messages With Python using Pywhatkit module
We can automate a Python script to send WhatsApp messages. In this article, we will learn the easiest ways using pywhatkit module that the website web.whatsapp.com uses to automate the sending of messages to any WhatsApp number. Installing pywhatkit module: pywhatkit is a python module for sending Whatsapp messages at a certain time. To install the
4 min read
Building Calculator using PyQt5 in Python
In this article we will see how we can create a calculator using PyQt5,A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display. below is the how the calculator will looks like GUI implementation steps Create a label to show the numbers and the output and set i
5 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Building a basic HTTP Server from scratch in Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC, or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation: On the terminal run the following state
2 min read
Building a Simple Application using KivyMD in Python
KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we will see how to make a simple application in KivyMD using Screen, Label, TextFieldInput, and Bu
3 min read
Building CLI to check status of URL using Python
In this article, we will build a CLI(command-line interface) program to verify the status of a URL using Python. The python CLI takes one or more URLs as arguments and checks whether the URL is accessible (or)not. Stepwise ImplementationStep 1: Setting up files and Installing requirements First, create a directory named "urlcheck" and create a new
4 min read
Building Space Invaders Using PyGame - Python
In this article, we're going to build a Space Bullet shooter game using PyGame in Python. The used file can be downloaded from here. Approach: Import the required module.Initialize the pygame.Create three functions:isCollision(): Which tells us whether the collision has occurred or not?game_over(): Which returns True or False on the basis of which
13 min read
Building Flutter Apps in Python
In this article, Here we will use Flutter apps in Python, for this library Flet will help to Build the Application. What is Flet? Flet is a Python Library using which developers can build real-time web apps, Mobile Apps, and Desktop apps without directly using Flutter. As to building apps using Flutter, developers need to learn Dart language but us
9 min read
Building A Weather CLI Using Python
Trying to know the weather is something that we all do, every day. But have you ever dreamed of making a tool on your own that can do the same? If yes, then this article is for you. In this article, we will look at a step-by-step guide on how to build a Weather CLI using OpenWeather API. What is OpenWeather API?OpenWeather API is a weather API prov
4 min read
Building a terminal based online dictionary with Python and bash
I was watching a movie yesterday and I didn’t understand some of the words used. So what I did was, each time I didn’t understand any word, I’d fire up my browser and type in ‘define [word]’ and google would turn me up with the meaning of the word. But it’s annoying to open the browser every time (Blame me for that ;P). What do we geeks users love
4 min read
Building a Background PDF Generation App Using Python Celery and Template Data
In today's digital age, businesses often require the generation of PDF files with dynamic data for various purposes such as reports, invoices, or certificates. However, generating these PDF files synchronously within a web application can lead to performance issues and user experience degradation. To solve this, we can create a background app that
3 min read
Building Powerful Telegram Bots with Telethon in Python
Creating a Telegram bot can significantly enhance how you interact with users, automate tasks, and provide information quickly. Here, we'll use the Telethon library in Python to build a powerful Telegram bot. Creating Telegram Bot in PythonPrerequisites Telegram Account: We need a Telegram account to create and manage our bot.Telethon Library: We'l
4 min read
Tableau - Building up a storyline
Visualisations are a part of business analysis. But it is also very important to communicate your findings effectively. Tableau 10 includes stories, which were first introduced in an update to version 8. Using stories, you create a sequence of story points consisting of worksheets in your workbook. You can use them to build a persuasive narrative a
2 min read
Practice Tags :
three90RightbarBannerImg