# Receive WhatsApp messages using Python

In this guide, we'll demonstrate how you can set up a Python server application that can receive WhatsApp messages using a webhook. This approach is fantastic for facilitating timely interactions with your clients. Ready to get started? Let's dive in!

{% embed url="<https://youtu.be/OnLtP2tHOk4>" %}

{% hint style="success" %}
By the way, we have the source code of a great Python chatbot: <https://github.com/Whapi-Cloud/python-whatsapp-chatbot>. It can handle incoming messages, try it!
{% endhint %}

### Introduction

Webhooks are a valuable instrument for achieving real-time updates. They send data every time a particular event is triggered. In this tutorial, we'll instruct you on creating a simple Python application to function as your webhook, which will receive incoming WhatsApp messages.

{% hint style="info" %}
Detailed manual about webhooks [here](https://support.whapi.cloud/help-desk/receiving/webhooks)
{% endhint %}

### Preparations

1. **Python**: Python 3.6 or later should be installed on your server or local computer. You can download the latest version of Python from the [official website](https://www.python.org/).
2. **Flask**: Flask is a lightweight web server framework for Python that we'll be using to handle incoming HTTP requests. It can be installed using pip, which is Python's package installer, with the command `pip install flask`.
3. **Whapi.Cloud Account**: We'll use the Whapi.Cloud service to interface with WhatsApp. If you haven't already, [sign up here](https://panel.whapi.cloud/register).

### Setting Up Your Webhook on Whapi.Cloud

Prior to crafting our Python code, we'll need to set up a webhook URL on Whapi.Cloud. Here's how you can do this:

1. Sign in to your Whapi.Cloud account and go to your Channel Dashboard.
2. Click on 'Settings', then 'Webhook'.
3. Fill in the URL where Whapi.Cloud will send the incoming messages. This should be the address of the Python app we're going to create.
4. Save your changes to confirm.

<figure><img src="https://2417185145-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhsdgGmVCG31mEaHyRvxC%2Fuploads%2FGx0qUi02KFNpriZPZoi5%2Fsettings-whapi.png?alt=media&#x26;token=25ce50f5-869f-4a1f-a175-8fa8c2481274" alt=""><figcaption><p>Settings</p></figcaption></figure>

<figure><img src="https://2417185145-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhsdgGmVCG31mEaHyRvxC%2Fuploads%2FkuOwISTbkAXB5PUxSrZp%2Fhook-settings.png?alt=media&#x26;token=49ff8f65-4c9d-4591-943e-39b30ecb821b" alt=""><figcaption><p>Webhook settings</p></figcaption></figure>

#### Sample Message Format

If you're using Whapi.Cloud's WhatsApp API and have set up a webhook URL, you'll receive incoming messages in a JSON structured format.

```json
{
  "messages": [
    {
      "id": "IINCYddajIbJxaBbi0gwXQ-gOUSdTZG3w",
      "from_me": false,
      "type": "text",
      "chat_id": "15055913687@s.whatsapp.net",
      "timestamp": 1696502988,
      "text": {
        "body": "Hello"
      },
      "from_name": "Alexander"
    }
  ]
}

```

**Sample Python Script**

Create a new file named `webhook.py` in your project's root directory. The code for your webhook is as follows:

```python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def whatsapp_webhook():
    data = request.json
    for message in data['messages']:
        if not message['from_me']:
            chat_id = message['chat_id'].split('@')[0]  # Extracting phone number from chat_id
            text = message['text']['body']

            # Here, you can process the message as required
            # For demonstration, let's just print it
            print(f"Received message from {chat_id}: {text}")
            
            # Extend below to store in a database, send an email, etc.

    return jsonify(status='success'), 200

if __name__ == '__main__':
    app.run(debug=True)
```

This Python script, built using the Flask framework, sets up a server to listen for incoming POST requests at the `/webhook` endpoint. When a request (representing a new WhatsApp message) arrives, the script extracts the sender's phone number and the message content. The script then logs this information, but you can expand on this foundation, for instance, by integrating with a database or implementing custom response logic based on the message content.

Of course, you may want to adapt this script to suit your needs.

To use this script, ensure you have Flask installed (`pip install Flask`). Run the script to start a server on your local machine, typically accessible at `http://127.0.0.1:5000/`. Ensure your webhook URL points to this endpoint to start receiving and processing messages.

### Conclusion

Bravo! You've now equipped your Python server with the ability to receive WhatsApp messages in real time. This will undoubtedly streamline your interactions with customers, especially when dealing with a high volume of messages.

Enjoy exploring the capabilities of your new webhook! If you encounter any difficulties or have any inquiries, please don't hesitate to get in touch. We're always here to support you!


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://support.whapi.cloud/help-desk/receiving/webhooks/receive-messages/receive-whatsapp-messages-using-python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
