Receive WhatsApp messages using Python

How to Receive WhatsApp messages using Python and webhook

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!

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!

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.

Detailed manual about webhooks here

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.

  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.

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.

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.

{
  "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:

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!

Last updated