DEV Community

Cover image for Creating a WhatsApp Bot with Python: a step-by-step guide for developer
WhatsApp API for developers
WhatsApp API for developers

Posted on • Updated on

Creating a WhatsApp Bot with Python: a step-by-step guide for developer

For those who don't have time to read:
Source code of a powerful WhatsApp bot on GitHub

In this tutorial, we aim to guide you through the process of developing a WhatsApp bot using Python, leveraging the capabilities of Whapi.Cloud. Python, renowned for its simplicity and readability, is a versatile programming language suitable for a wide array of applications, including bot development.

Image description

By the end of this guide, you’ll have the foundational knowledge and practical experience necessary to develop and extend your own WhatsApp bot, paving the way for countless possibilities in enhancing communication and interaction through automated technology. Whether you are aiming to create a bot for customer support, content distribution, or task automation, this tutorial will provide you with the insights to kickstart your journey in WhatsApp bot development using Python.

Preparing the Working Environment

Before delving into the development of the bot, it is crucial to prepare the development environment by installing Python and setting up the necessary libraries and tools.

Installing Python

If you haven’t installed Python yet, you can download it from the official Python website. Python 3.6 or newer is recommended, as it includes many new features and optimizations. The installation process is straightforward, and you can follow the prompts to complete it.

Setting Up a Virtual Environment

Once Python is installed, it’s a good practice to create a virtual environment. A virtual environment is an isolated Python environment in which you can install libraries and dependencies without affecting the global Python installation. To create a virtual environment, open a terminal or command prompt and run the following commands:

$ mkdir whatsapp_bot
$ cd whatsapp_bot
$ python3 -m venv venv
Enter fullscreen mode Exit fullscreen mode

To activate the virtual environment:
$ .\venv\Scripts\activate
On MacOS/Linux:
$ source venv/bin/activate

Installing Necessary Libraries

After activating the virtual environment, you’ll need to install the libraries essential for the development of the bot. For this tutorial, we are primarily using Flask for handling HTTP requests and the requests library for interacting with the Whapi.Cloud API.

$ pip install Flask requests

Choose an Integrated Development Environment (IDE) that you are comfortable with. PyCharm, Visual Studio Code, and Jupyter are excellent choices. Once chosen, configure your IDE to use the virtual environment you’ve created as the Python interpreter.

Connecting to the WhatsApp API

Whapi.Cloud is an API gateway that facilitates integration with WhatsApp. This makes it possible, with the Cloud API’s tight restrictions and expensive messages, to fully automate any messenger functionality. In this article, we will look at just a few methods for sending, receiving and processing messages in WhatsApp, but the possibilities of this tool are much more.

Connecting to the Whapi.Cloud for WhatsApp automation is a foundational step in creating your WhatsApp bot.
Registration on Whapi.Cloud

To kickstart your journey, register on Whapi.Cloud by creating a free account. This step is straightforward and doesn’t require any credit card details. Post-registration, you gain immediate access to a test channel, albeit with some limitations.

Connecting Your Phone

The test channel requires around a minute to initiate. After its activation, connect your phone to enable WhatsApp automation. The service will utilize your connected phone to send messages. Here’s a step-by-step process:

  1. Access the QR code by clicking on your trial channel in your Whapi.Cloud account.
  2. Open WhatsApp on your mobile device.
  3. Navigate to Settings -> Linked devices -> Link a device -> Scan QR code.

This swift connection process is a standout feature of Whapi.Cloud, enabling you to launch and operate within minutes.

Image description

Channel Customization and Configuration

During the second and third steps of the connection, you’ll be prompted to personalize your channel. You can name your channel, configure webhooks, and modify other settings as per your preference. However, these steps can be skipped initially and revisited later for refinement.

Obtaining API Token

Once your channel is operational, locate your API Token in the center block beneath the limits information. This token is pivotal for authenticating your API requests. Typically, it is included in the request headers as a Bearer Token or as a request parameter, adapting to the API method employed.

Using Webhooks

Webhooks are crucial for managing incoming messages effectively. They can be configured in the settings of your Whapi.Cloud account. When a message is received, the configured webhook URL will receive a POST request containing the message data, allowing your bot to process incoming messages and respond accordingly. We will delve deeper into the usage of webhooks in the upcoming sections.

Webhooks for WhatsApp API | How to receive incoming message | How to get the status of a message - YouTube

When developing a WhatsApp chatbot or integrating with any CRM, questions often arise: How to receive a message? How to process an incoming message? How to g...

favicon youtube.com

Image description

Send WhatsApp message using Python

Once the preliminary setup is complete and your environment is prepared, the next fundamental step is sending a simple message. Python, with its rich library set, provides a succinct and straightforward way to perform this using the requests library, which is widely used for making HTTP requests.

Below is a basic example that demonstrates how to send a simple text message using Python.

import requests

url = "https://gate.whapi.cloud/messages/text?token=YOUR_TOKEN"

payload = {
    "typing_time": 5,
    "to": "1234567891@s.whatsapp.net",
    "body": "Hello, world!"
}
headers = {
    "accept": "application/json",
    "content-type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

In this example:

  • url: This is the endpoint provided by Whapi.Cloud for sending text messages, including the API token.
  • payload: It holds the parameters like typing_time (how long the user sees the "typing..." status), to (the recipient's WhatsApp number with the domain @s.whatsapp.net), and body (the actual message text).
  • headers: These are used to set the content type to JSON.

A list of all parameters is available in the documentation

Executing the script will send a “Hello, world!” message to the specified WhatsApp number, and the server’s response will be printed to the console.

Explanation

The requests.post() method initiates an HTTP POST request to the specified URL. The json=payload argument is used to send the payload in JSON format, and the headers=headers argument sets the request headers to inform the server about the type of content being sent.

Once the message is successfully sent, the response.text will print the server's response, providing information about the success or failure of the message sending.

Handling Incoming Messages

Handling incoming messages is a pivotal step in the development of a WhatsApp bot. In this chapter, we will cover the concept of a webhook, its utility, the setting process via the dashboard or API, and the fundamental logic to handle and respond to incoming messages.

What is a Webhook?

A webhook is an HTTP callback that occurs when something happens; it’s a simple way for apps to communicate with each other. In the context of WhatsApp bots, a webhook is used to receive incoming messages or event notifications from WhatsApp users. Whapi.Cloud allows the setting of multiple hooks with various modes (Body, Path, Method) for different events (Message, Ack, Chat, Status), offering flexibility and extensive coverage for various use cases.

Setting up Webhook via Interface and API

Image description

You can set up webhooks either through the interface on your personal account on Whapi.Cloud or programmatically via API. Below is a Python snippet on how to set it up through API:

import requests

url = "https://gate.whapi.cloud/settings?token=YOUR_TOKEN"

payload = {
    "callback_backoff_delay_ms": 3000,
    "max_callback_backoff_delay_ms": 900000,
    "callback_persist": True,
    "pass_through": True,
    "sent_status": False,
    "webhooks": [
        {
            "events": [
                {
                    "type": "messages",
                    "method": "post"
                },
                {
                    "type": "ack",
                    "method": "post"
                }
            ],
            "mode": "body",
            "url": "<Webhook URL, http or https>"
        }
    ]
}
headers = {
    "accept": "application/json",
    "content-type": "application/json"
}

response = requests.patch(url, json=payload, headers=headers)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

In this script:

  • The url is the Whapi.Cloud endpoint to adjust settings, inclusive of the API token.
  • The payload holds the webhook configurations.
  • The webhooks array in the payload specifies the events and the URL where the webhook will send the HTTP POST request when the events occur.

The unique feature and advantage of Whapi.Cloud are that it allows setting up multiple webhooks with varying modes on different events, providing versatility and a broader range of interaction capabilities. This feature allows the development of more sophisticated and responsive bots, enhancing user interaction and experience.

For creating a server that will handle incoming messages, we will be using Flask, a lightweight WSGI web application framework in Python. In this example, the bot will be responding to incoming messages and, depending on the received command, it will be sending different replies.

Below is a sample code for the bot (python code to send and receive whatsapp message):

from flask import Flask, request
import requests

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    # Retrieving incoming message
    incoming_message = request.json

    # Retrieving the text of the message
    message_text = incoming_message.get('body', '').lower()

    # Deciding the reply based on the command
    if message_text == 'hello':
        response_text = 'Hi! How can I assist you today?'
    elif message_text == 'info':
        response_text = 'I am a WhatsApp bot created to assist you!'
    else:
        response_text = 'I am sorry, I do not understand the command.'

    # Sending the reply message
    send_message(response_text, incoming_message['from'])

    return '', 200

def send_message(response_text, to):
    # URL to send messages through the Whapi.Cloud API
    url = "https://gate.whapi.cloud/messages/text?token=YOUR_TOKEN"

    # Forming the body of the message
    payload = {
        "to": to,
        "body": response_text
    }
    headers = {
        "accept": "application/json",
        "content-type": "application/json"
    }

    # Sending the message
    response = requests.post(url, json=payload, headers=headers)
    print(response.text)

if __name__ == '__main__':
    app.run(port=5000, debug=True)
Enter fullscreen mode Exit fullscreen mode

In this sample:

  • We are creating a web server using Flask and setting up a webhook on the /webhook endpoint.
  • When the bot receives a new message, it analyzes the text of this message and sends an appropriate reply using the send_message function, in which we employ the message-sending code from previous Chapter.

Source code of ready-made simple Python WhatsApp chatbot

Here is an example of a complete code to create a simple WhatsApp bot using Python.

Source code of a powerful WhatsApp bot on GitHub

In this code sample:

  • When a text message is received, the bot responds by repeating the received text.
  • We create a group and show how to send different types of messages

Please replace YOUR_API_TOKEN with your real API token from Whapi.Cloud. This code is a basic example and can be augmented with other functions and handlers to create more complex and interactive bots.

Extending Functionality

In this chapter, we will delve into extending the functionality of our WhatsApp bot, enabling it to send media messages, create groups, count users in a group, and handle incoming group messages.
Sending WhatsApp Media Messages

Sending media messages involves transmitting different types of media like images, videos, gifs, audio, voice notes, documents, and stickers through WhatsApp. Here is an example of how you can send an image:

import requests

url = "https://gate.whapi.cloud/messages/media/image?caption=Name%20of%20pic&to=1234567891%40s.whatsapp.net&mentions=&token=YOUR_TOKEN"

payload = "data:image/png;name=Untitled2.png;base64,iVBORw0KGgoAAAANSUhEUgAAAx...V//5Tq42UXih5JAAAAAElFTkSuQmCC"
headers = {
    "accept": "application/json",
    "content-type": "application/pdf"
}

response = requests.post(url, data=payload, headers=headers)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

In the example above:

  • url specifies the API endpoint for sending images, with a caption and a recipient included as parameters.
  • payload contains the base64 encoded image along with its name.
  • The content-type in headers specifies the type of media being sent, and in this case, it is an image.

This method can be generalized to send other types of media by modifying the url and content-type accordingly, ensuring they match the media being sent.

WhatsApp API Group Management

Retrieving Group Details and Counting Participants

To retrieve the details of a group, including the participants, you can make a GET request to the respective endpoint provided by Whapi. Below is an example of how to retrieve details of a group:

import requests

url = "https://gate.whapi.cloud/groups/120363175154208908%40g.us?token=YOUR_TOKEN"

headers = {"accept": "application/json"}

response = requests.get(url, headers=headers)

print(response.text)
Enter fullscreen mode Exit fullscreen mode

The response from this request will contain various details about the group, such as its ID, name, type, timestamp, and a list of the participants along with their ranks within the group. Here’s an example of the response:

{
  "id": "120363175154208908@g.us",
  "name": "Hello",
  "type": "group",
  "timestamp": 1694784032,
  "not_spam": true,
  "participants": [
    {"id": "14406616972", "rank": "creator"},
    {"id": "15057426924", "rank": "member"},
    {"id": "15056452483", "rank": "member"}
  ],
  "name_at": 1694612985,
  "created_at": 1694612985,
  "created_by": "14406616972"
}
Enter fullscreen mode Exit fullscreen mode

To count the number of participants in the group, you can simply calculate the length of the participants list in the response. Here’s how you can do it:

import requests
import json

url = "https://gate.whapi.cloud/groups/120363175154208908%40g.us?token=YOUR_TOKEN"

headers = {"accept": "application/json"}

response = requests.get(url, headers=headers)

group_data = json.loads(response.text)
participants_count = len(group_data['participants'])

print(f'The number of participants in the group is {participants_count}.')
Enter fullscreen mode Exit fullscreen mode

In this example, json.loads(response.text) is used to convert the JSON response string into a Python dictionary, enabling you to access the participants list and calculate its length to determine the number of participants in the group.

More methods to automate Groups on Whatsapp can be found here

Testing and Debugging: Local Testing

When developing a bot, it is essential to continuously test and debug your application to ensure that it is working correctly and is free of errors. For local testing, you can use Postman or any other API testing tool to simulate incoming messages and check the responses from your bot.
Try for Free

Additionally, you can use Python’s built-in logging module to log important information, errors, and exceptions that can occur during the execution of your bot, which will assist in identifying and resolving issues more efficiently.

Here’s a brief example of implementing logging in your Python application:

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

try:
    # Your bot logic here
    pass
except Exception as e:
    logger.exception("An error occurred: %s", e)
Enter fullscreen mode Exit fullscreen mode

Deployment and Hosting

Once you have thoroughly tested your bot and are satisfied with its functionality, it is time to deploy it to a server. You can host your bot on any cloud service provider like AWS, Google Cloud, or Azure, or on any server that supports Python.

Consider using services like Docker to containerize your application, making it easier to manage, scale, and deploy. Also, make sure to secure your application, especially if it handles sensitive data, by implementing proper authentication and encryption mechanisms.

Conclusion and Next Steps

By now, you should have a fully functional WhatsApp bot that can interact with users, process incoming messages, and send different types of media. The combination of Python and Whapi.Cloud makes it relatively straightforward to build robust and versatile WhatsApp bots, but this is just the beginning.

Image description

Continue to build on your bot by adding more advanced features, like natural language processing for more intelligent interactions, or integrating with other APIs to expand the functionality.

In our detailed documentation, you’ll find step-by-step instructions and sample methods that allow you to send a variety of message types, from any file format, locations, and contacts to stickers, audio, polls, and merchandise. In addition, you can dynamically interact with your messages: putting reactions, quoting them, marking them as read, or simulating real-time printing.

Our methods in documentation will automate your business: send products and catalog for leads, process shopping cart, return those who abandoned the cart. Send surveys as feedback collection. Create bots to book seats for events, etc.

Please replace YOUR_API_TOKEN with your real API token from Whapi.Cloud. This code is a basic example and can be augmented with other functions and handlers to create more complex and interactive bots.

Get Started Free

Top comments (10)

Collapse
 
prajwal_ramenops profile image
Prajwalicious 🍜

will this cost?

Collapse
 
whapicloud profile image
WhatsApp API for developers

The first three days are free.
Then either a free developer rate (it is completely free, but has a limit on the number of conversations and messages), or a paid rate (for one channel from $29 per month with an annual payment).
There is a flexible pricing terms for partners and white label which allows for great discounts.

Collapse
 
whapicloud profile image
WhatsApp API for developers • Edited

But for DEV Community members we will be ready to make a discount) While we are developing a system of promo codes, but if someone is interested, just write in the support chat that you are from here and you will get a 20% discount on the first payment

Collapse
 
marcitpro profile image
Marcitpro

Great post

Collapse
 
whapicloud profile image
WhatsApp API for developers

Thx!

Collapse
 
whapicloud profile image
WhatsApp API for developers

Uploaded the source code of a powerful bot on GitHub (Python)
github.com/Whapi-Cloud/python-what...

Collapse
 
whapicloud profile image
WhatsApp API for developers • Edited

Made by developers for developers <3
WhatsApp API Platform

Collapse
 
gdledsan profile image
Edmundo Sanchez

why whappi and not straight to the whatsapp API?

Collapse
 
whapicloud profile image
WhatsApp API for developers

Thank you for your question. The official solution has a lot of limitations, and yet is not available due to inspections and cost to a small business or individual. We have developed an independent solution that provides many times more functionality and is less expensive. Read more about the comparison here: whapi.cloud/whatsapp-business-api-...

Collapse
 
gautam121 profile image
gautam

Take your business to the next level with Whatsapp business API