A detailed guide to developing a WhatsApp chatbot in Python. With Whapi.Cloud, you can quickly and easily create an integration or bot that can send and receive messages, handle any media files, work with groups, stories, and channels.
WhatsApp Automation with Python
WhatsApp has long ceased to be just a messenger — it has become a vital tool for business. Automating client communication via chatbots and integrating messenger into CRMs unlocks new opportunities for efficiency and better service. Python is an excellent choice for this task due to its flexibility and accessibility, while Whapi.Cloud provides easy access to the API with excellent support, always ready to assist.
In this guide, we will cover:
How to work with WhatsApp API using Python;
Integration with Whapi.Cloud for automating various tasks;
Using webhooks to handle and auto-respond to messages;
The purpose of this article is to demonstrate step-by-step how to create a simple yet useful WhatsApp chatbot in Python. If you have any questions or difficulties, feel free to contact us through our chat widget on the website — we’ll respond promptly! To make your work easier, you can use our ready-made Python bot scripts published on GitHub. These projects provide detailed setup and testing instructions, and the code contains useful comments. It’s an excellent starting point for beginner developers.
Getting Ready to Develop a Bot
Before getting started, make sure you have everything you need:
Python. Install Python if you haven’t already. Download the latest version (3.6 or above recommended) from the official site and follow the installation instructions.
Flask. Flask is a lightweight Python web framework that we’ll use to set up a server and handle webhooks. Install Flask using the command: pip install Flask.
API Token. Register on Whapi.Cloud to get an API token. This token allows your bot to interact with messenger through the API. After registration, you’ll receive a free channel with limited features, sufficient for testing your development. Whapi.Cloud stands out for its stability, low cost, and wide range of features. We’ll provide instructions on obtaining the token below.
Configured Webhook. To enable your bot to process incoming updates and events from WhatsApp, you’ll need a server URL (local or external) to handle notifications from messenger. This article will explain in detail how to set it up and where to get such a link.
On GitHub, you will find several repositories with different bots. One of them is considered ideal for beginner programmers as it has very simple but understandable functionality—sending text messages and images in response to commands. Another bot version is suitable for more advanced users, as it includes more features: Sending plain messages, images, files, videos, contacts (vCard), products, creating new WhatsApp groups, sending invitations, and sending messages to groups.
If you want to learn more about the differences between WhatsApp Business API and WhatsApp API or are unsure about which provider to choose, we recommend reading our article "How to Choose WhatsApp API: Comparing Solutions and Providers". It will help you make an informed choice and avoid future issues or unnecessary expenses.
If you haven’t registered on the Whapi.Cloud platform yet, do so right now. Registration is simple, doesn’t require credit card information, and grants you 5 days of full API access with minor limitations. This is more than enough to test all methods and functions and set up your bot or integration.
The next step is to connect a number. There’s no need to go through moderation or number migration steps. Connect any number you already use in your WhatsApp application. Your chatbot will continue working even if the phone is offline, so there’s no need to keep the device active constantly.
To connect a number:
1.
Go to the dashboard and open the Default Channel page that’s already created for you.
2.
At the first step, you’ll see a QR code with instructions.
3.
Open WhatsApp on your device, go to Settings → Linked Devices → Link a Device → Scan QR Code.
4.
After successful connection, name the channel (e.g., "My Chatbot") for easier management in the future.
Next, you’ll see the settings window, but it’s not required now — you can skip this step, and we’ll return to it later.
Go to the WhatsApp settings on your phone
Scan the QR code in your WhatsApp
To connect your phone, use the QR code
Write channel's name for your convenience, set webhooks, change settings
Getting an API Token
On the connected channel page, you’ll find your unique API token in the center. This token is critical for authenticating requests. It’s passed in request headers as a Bearer Token or as a parameter, depending on the method.
Your API Key
Tools for Working with the API
Whapi.Cloud offers several ways to access API documentation:
User-Friendly Developer Hub: A specialized platform with documentation and examples provides code snippets for all endpoints in various programming languages.
Postman Collection: Ready-made requests for testing the API through Postman.
Swagger File: A detailed description of all API methods, with testing capabilities directly from the channel page.
These tools help developers of any level quickly understand the Toolkit features and start integration. One of Whapi.Cloud’s key advantages is the ease of setup: you can start working with the API in just a few minutes.
What is a Webhook and How to Set It Up?
To enable full interaction between your bot and our gateway, you need to set up a webhook. This ensures data exchange between systems: your bot will promptly receive incoming texts, message status updates (e.g., "sent," "delivered," "read"), or notifications about other events.
What is a Webhook?
A webhook is an HTTP callback that sends data from our server to your server when a specific event occurs on WhatsApp. For example, as soon as your client sends a message, your server automatically receives a notification about the incoming message.
The main benefits of webhooks:
Instant notifications. All events are processed almost in real-time.
High throughput. Notification speed is only limited by your server's performance.
Flexibility. You can receive only the events you truly need, such as: Personal and Group messages; Message status changes; Group participant changes; Missed call notifications; Channel statuses, and much more.
Whapi.Cloud provides you with a convenient tool for configuring webhooks, allowing you to flexibly manage notifications in the format you need and tailor them to your tasks.
How and Where to Get a Webhook URL?
To ensure your integration or bot can receive and process information from messenger in real-time, you'll need a server URL where the bot script will be hosted to accept the data. If you're unsure where to get such an address, we’ve prepared a detailed guide: "Where to find the Webhook URL?". The article explains in detail how to set up a local server or choose an external hosting. Below, we’ll cover a simple and quick way to get such a link using Ngrok.
Technically, when a message is received on your WhatsApp, our server will send a POST request with a JSON body to your script’s URL. The JSON body will include all information about the incoming message, such as text, sender number, sending time, etc., allowing you to process this information in real-time.
The simplest way to get a URL for local use is to choose a tool like Ngrok, which creates a secure tunnel to your localhost, allowing you to access your local server from the Internet.
1) Download Ngrok from the official website and extract it. Open the terminal and navigate to the folder where Ngrok is stored.
2) Run ./ngrok http PORT_NUMBER, replacing PORT_NUMBER with the port your Flask server is running on locally (e.g., 80).
3) You should now have a public URL that you can use as the webhook URL. Copy it for further use.
Launch Ngrok and get a free link
Channel settings interface in the dashboard
Setting Up a Hook on a Channel
Once you have a working webhook URL, follow these steps:
Go to the channel settings. On the channel page, click the settings button (top right corner).
Configure the webhook. Enter your URL in the webhook section using preselected settings. You can set up multiple webhooks for different events if necessary. These settings can also be adjusted via the API.
Save the changes. From now on, all notifications about WhatsApp events will be sent to the server you specified.
For example, if a message arrives at your server, the webhook will send a POST request with the message data. Your task is to process this data and program the bot to respond accordingly. In the next part of the article, we’ll discuss how to do this.
Creating the Basics of a WhatsApp Bot in Python
In this section, we’ll cover how to use the Whapi.Cloud API to send and manage messages on WhatsApp using Python. We assume you already have the environment set up: Python installed, an API token obtained, and a project created with an index.py file.
Installing required libraries.
To interact with the Platform, we’ll need to install several libraries. You can either install them individually or compile a dependency list in a requirements.txt file and install them with a single command.
Using a .env file.
For convenience in working with tokens and other environment variables, create a .env file. This allows you to store sensitive data separately from the code, making it easier to update.
Example of .env file content:
API_TOKEN=8FjpwmyFUulh7emXOprrET3xKrwJ984O # API token from your channel
API_URL=https://gate.whapi.cloud # API endpoint URL
PORT=80 # example, 80 or 443
#URL_LINK= The Webhook link to your server {link to server}/hook.
You can load environment variables into your script using the python-dotenv library:
from dotenv import load_dotenv
import os
load_dotenv()
api_token = os.getenv("API_TOKEN")
Sending a Text Message
Let’s start with a simple example: sending a text message. The token must be passed in the authorization header (Bearer), and the request body should contain the message parameters.
import requests
# URL for sending text messages. Can be pulled from .env
url = "https://gate.whapi.cloud/messages/text"
# Data for sending a message
payload = {
"to": "919984351847", # Enter the recipient's number in international format
"body": "Hello! This is a test message." # Text of message
}
# Headers, including authorization token
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": f"Bearer {api_token}" # Use the token from the .env file
}
# Sending a POST request
response = requests.post(url, json=payload, headers=headers)
# Output server response
print(response.status_code)
print(response.text)
After successfully sending the message, you can try more complex scenarios, such as delivering images, files, or interacting with groups. Simply follow the examples of requests in our API documentation. We’ll discuss this in the next chapters. For now, ensure your message is sent correctly and the server returns a 200 OK status.
Receiving Messages via Flask Webhook
To process incoming content, you need to configure a Flask route that will serve as the webhook endpoint. This route will receive data from Whapi.Cloud, transmitted as POST requests when events occur (e.g., receiving a message).
After configuration, you need to update the webhook URL in your Whapi.Cloud channel by specifying the URL you created. In this example, we use https://your_domain_or_ip/hook. Remember, this can be an external server or a local one. Ensure this link is functional and accepts requests. You can always check the availability of your webhook link using our endpoint.
A simple variation of processing incoming messages:
from flask import Flask, request, jsonify
app = Flask(__name__)
# Route for processing incoming messages
@app.route('/hook', methods=['POST'])
def webhook():
# Retrieving data from a request
data = request.json
# Logging an incoming message
print("Received message:", data)
# Example of incoming message processing
if "messages" in data:
for message in data["messages"]:
sender = message["from"] # Sender's number
text = message.get("body", "") # Text of message
print(f"Message from {sender}: {text}")
# Logic for replying to a message
# Check out our examples on GitHub, where we use more branching on commands for the bot
if text.lower() == "hello":
send_response(sender, "Hi there! How can I help you?")
elif text.lower() == "bye":
send_response(sender, "Goodbye!")
return jsonify({"status": "success"}), 200
# Function for sending a reply
def send_response(to, body):
import requests
url = "https://gate.whapi.cloud/messages/text"
payload = {
"to": to,
"body": body
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": f"Bearer {api_token}" # Use the token from the .env file
}
response = requests.post(url, json=payload, headers=headers)
print(f"Response to {to}: {response.status_code}, {response.text}")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
In this code, we set up a Flask route (make sure the Flask server is running). Ensure your webhook is working correctly and returns a proper 200 response.
Now your bot can automatically respond to incoming notifications and perform actions depending on their content. To simplify the process of writing a bot from scratch, you can use our ready-made Python bot scripts, published on GitHub. These projects include detailed setup and testing instructions, as well as helpful comments in the code. It’s an excellent start for beginner developers.
On GitHub, you will find several repositories with different bots. One of them is considered ideal for beginner programmers as it has very simple but understandable functionality—sending text messages and images in response to commands. Another bot version is suitable for more advanced users, as it includes more features: Sending plain messages, images, files, videos, contacts (vCard), products, creating new WhatsApp groups, sending invitations, and sending messages to groups.
In the next chapter, we’ll look at advanced features, such as sharing multimedia and interacting with groups.
Advanced Features
With Whapi.Cloud, you gain access to an impressive set of tools and features that allow you to create chatbots of any complexity.
We offer step-by-step instructions and examples of using various Endpoints and SDKs to help automate a wide range of tasks: send text messages, files of any format, geolocation, contacts, stickers, polls, products, and more. React to messages with emojis, quote them, mark them as read, pin conversations, activate the 'typing...' status. Automatically create and delete groups and communities, add and remove group members, set administrators, adjust group parameters and settings, block users, and much more.
Thanks to these features, integrating a bot with your website, application, CRM, ERP, or other systems becomes a straightforward and clear process. Whapi.Cloud provides developers with all the necessary tools for flexible and quick integration.
All methods and their capabilities are described in detail in our documentation. Start automating today to unlock new opportunities for your business!
Interactivity and visual content can significantly enhance user engagement when communicating with your WhatsApp bot. Sending images via the Integration allows companies to share products, promotions, or important text in a visual format, making interactions richer and more effective. Now, let’s examine how to send an image through the WhatsApp API using Python:
Expanding the functionality of your bot to include file sharing makes it an essential tool for exchanging important information. This can be useful for posting invoices, contracts, price lists, and other documents. Let’s explore how to implement file sending via the WhatsApp API using Python:
import requests
url = "https://gate.whapi.cloud/messages/document"
payload = {
"to": "919984351847",
"media": "data:application/pdf;base64,JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9UaXRsZSAoVGVybXMgb2YgU2VydmljZSBXaGFwaS5DbG91ZCkKL0NyZWF0b3IgKE1vemlsbGEvNS4wIFwoV2luZG93cyBOVCAxMC4wOyBXaW42NDsgeDY0XCkgQXBwbGVXZWJLaXQvNTM3LjM2IFwoS0h............",
"filename": "Terms of Service Whapi.Cloud.pdf",
"caption": "Hello, I am attaching an important file to my message"
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": "Bearer Your_Token"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
Creating a WhatsApp Group in Python
With Whapi.Cloud, you can not only create groups but also manage them dynamically. For example, add members, change the group name, assign administrators, and delete groups that are no longer needed. Let’s look at how to create a group via the WhatsApp API using Python:
Various issues can arise during the testing and operation of the WhatsApp chatbot. Here are a few typical situations and recommendations for their resolution:
The Bot Does Not Respond to Incoming Messages
Ensure you are sending messages to the number on which the bot is running from a different phone. The bot will not be able to respond to messages sent from the same number.
If the bot does not respond to messages from other numbers, check the operation of webhooks. Use services to simulate webhooks, for example, Webhook.site, to ensure which path the callback requests are coming through. Afterwards, check if the path matches the one you have configured. Also, ensure your server responds with 200Ok.
If you encounter difficulties, do not hesitate to contact our technical support for help. You can write in the web chat widget on our site or email [email protected]. We will assist you and figure out exactly what's wrong with the webhook.
The Bot Sends Messages Non-Stop
Return to the original version of the code. Our script includes a check to determine whether a message is incoming or outgoing, to prevent getting into an infinite loop of sending messages. Infinite sending may occur if there is no check for outgoing messages in the code, causing the bot to call itself, or if there is a cyclic sending of messages in the code.
The Bot Works in Some Chats, But Not in Others
Check your tariff plan on Whapi.Cloud. If you are using the trial mode or the "Sandbox" tariff, interaction is limited to a certain number of chats per month (currently up to 5 chats). In such a case, the bot will not be able to process messages in the sixth chat and subsequent ones.
It's important to remember that many issues can be prevented by carefully checking your chatbot's configuration and logic before launching. Regularly updating your code and paying attention to the details of settings can help avoid most typical errors. And our support team is always in touch and ready to assist you!
To ensure your WhatsApp chatbot is available 24/7, it needs to be hosted on a reliable hosting platform. You can use your server, but in this chapter, we will consider the three most popular platforms - Firebase, AWS, and Heroku - and go through the basic steps of deploying your bot on each of them.
The choice of platform depends on your preferences, budget, and project requirements. Each of the considered platforms offers its unique features and advantages. Firebase and AWS Lambda provide powerful backend functionality without the need to manage a server, while Heroku offers simplicity in deploying applications based on Git.
Firebase
Firebase offers Cloud Functions functionality, allowing you to run your bot without worrying about server infrastructure. In our opinion, this is the most optimal option.
Create a new Heroku app through the console or using the command heroku create;
Link your Git repository to Heroku and perform deployment with the commands git push heroku master;
Set the webhook URL provided by Heroku.
Conclusion and Recommendations
Creating a WhatsApp bot using Python and Whapi.Cloud opens the door to extensive automation possibilities. By following this programmer's guide, you have gained not only basic functionality but also an understanding of how to use powerful Service tools effectively.
After successful local setup, it’s essential to consider deploying your bot in a production environment. Flask is excellent for development, but for stable real-time operation, consider using servers like Gunicorn or uWSGI. These provide better performance and reliability.
If you haven’t yet registered for our service, try it for free to test all the features. Follow the instructions in this article to launch your bot or integration as quickly as possible. If you have any questions, our support team is always here to help make the process as simple and effective as possible.
On GitHub, you will find several repositories with different bots. One of them is considered ideal for beginner programmers as it has very simple but understandable functionality—sending text messages and images in response to commands. Another bot version is suitable for more advanced users, as it includes more features: Sending plain messages, images, files, videos, contacts (vCard), products, creating new WhatsApp groups, sending invitations, and sending messages to groups.
Thank you for choosing Whapi.Cloud, and we hope your bot becomes an integral part of your business! We’ll always be here to help you 🚀
“Managing multiple WhatsApp groups is simple with Whapi.Cloud. I can oversee group activity, manage admins, and post updates effortlessly. It’s a perfect way to generate leads directly from WhatsApp groups.”
Group Management and Lead Generation from WhatsApp Groups
Carlos da Silva
“Our hotel uses WhatsApp to send guests essential check-in details like door codes. This ensures they always have the info they need. We can even process photos guests send, such as proof of checkout.”
Smart Hotel Communication for Check-In and Guest Support
Ana-Maria Ionescu
“We manage a WhatsApp Channel and use Whapi.Cloud to monitor similar channels and competitors, scraping the best deals and posting them for our audience.”
Automated Discount Channel Management
Katrin Schneider
“We use Whapi.Cloud to verify which numbers in our database are on WhatsApp by sending cascading broadcasts. This way, we filter our contacts, reduce marketing costs, and know our messages reach active users—maximizing campaign efficiency.”
WhatsApp Number Verification and Audience Filtering
Sergio Navarro
“Our hospital’s bot, powered by Whapi.Cloud, lets patients see available appointment slots for specific doctors and notifies them when test results are ready. It keeps everyone informed and reduces the time our team spends on manual updates.”
Hospital Bot for Appointment Scheduling and Notifications
Fernanda Oliveira
“We use personalized promotional offers to engage customers weeks after their purchase, sending out exclusive discount vouchers via WhatsApp. We also send a special offer for each customer’s birthday, which boosts loyalty and keeps them coming back.”
Customer Loyalty and Retention
Lukas Wagner
“As soon as an order ships, our customers get tracking details and delivery updates directly on WhatsApp. This real-time communication builds trust and reduces the number of inquiries we receive after purchase.”
Order Tracking and Delivery Updates
Matei Popescu
“If a customer leaves items in their cart on our site, WhatsApp Bot automatically sends a friendly reminder. This gentle nudge has significantly increased our checkout rate, helping us convert more sales.”
Abandoned Cart Reminders
Hans Müller
Inhouse Developed & Managed
What is Whapi.Cloud?
Straightforward and powerful! Whapi.Cloud is an intuitive API that enables you to seamlessly connect your business with WhatsApp. With Whapi.Cloud, you can focus on what really matters – growing your business. Enjoy endless integration possibilities, such as building support bots, scheduling appointments, sending WhatsApp notifications, and so much more. Plus, monitor everything effortlessly with webhooks. Getting started has never been easier!
Our service provides full control and management of WhatsApp groups, communities and channels.
Add dynamics and new features: media, buttons, reactions, stories, orders and products. All of these are available to you for customer interaction.
Our care team will respond quickly and help you with any questions you may have!