Help Desk
  • Getting Started
    • ๐Ÿ™ŒWelcome to Whapi.Cloud
    • ๐Ÿ’ฐPricing
    • โ˜•Partners
    • ๐Ÿš€Getting started
    • ๐Ÿ‘จโ€๐Ÿ’ปAPI Docs
      • Developer hubs
      • Swagger environment
      • Postman collection
  • Sending
    • Introduction
    • Send text message
      • Whatsapp API send message PHP
      • Whatsapp API send message Python
      • Whatsapp API send message Node JS
      • Whatsapp API send message ะก#
      • Whatsapp API send message Java
      • API integration with VB6
      • Whatsapp API send message GO (Golang)
    • Send video, audio, image, document
    • Send Group message
    • Send post to WhatsApp Channel
    • Send message with Buttons
    • Send Emoji
    • Overview of other methods for sending
      • Send Voice message
      • Send contact (vCard)
      • Send message reactions
  • Receiving
    • Introduction
    • Webhooks
      • Our webhooks (Tracked events)
      • Where to Find the Webhook URL?
      • Set the webhook link to the channel
      • Detailed webhook settings
      • How to check the webhook?
      • Incoming webhooks format
        • Incoming message
        • Sent message
        • Chats
        • Groups
        • Account and device status
        • Other
          • Presences
          • Views of stories (statuses)
          • Story (status) from your contacts
          • Calls
      • Receive messages
        • Receive WhatsApp messages using PHP
        • Receive WhatsApp messages using Node js
        • Receive WhatsApp messages using Python
    • HTTP API
      • Retrieve a Specific User's Chat History
      • Get a full-size picture in the response
      • Get order items
      • Get a profile picture of a chat or user
    • File expiration period
  • Groups
    • Send Group message
      • Mentioning all participants in a WhatsApp group
    • Get list of group members
    • Add new member to Group
  • Channels
    • Send post to WhatsApp Channel
    • Get messages from Channels
    • Get votes from polls in the Channel
  • Communities
    • Introduction
    • Create a community
    • Add a member to a community
    • Send announcement
    • Get info on community participants
    • Add a group / Exclude a group from the community
  • Account
    • Setting "Auto Download"
    • Customizable Webhook Headers
    • How to find out the IP channel
    • How to Delete a Channel
    • Add Business Info to Invoice
  • Source code
    • WhatsApp ChatBot
      • WhatsApp Python Bot
      • WhatsApp PHP Bot
      • WhatsApp Node JS Bot
      • WhatsApp Java Bot
    • WhatsApp API Google Sheets
    • WhatsApp Phone Number Checker
    • Request Distributor (Balancer)
  • FAQ
    • Chat ID. What is it and how to get it?
    • Current status of Buttons on WhatsApp
    • How to send a paragraph (line break)
    • Inactive Links in WhatsApp Messages
    • WhatsApp Text Formatting
    • Checking if the number has Whatsapp
    • Specifics of sending messages to numbers of different countries
    • Why aren't participants being added to the group?
  • Does WhatsApp API Work with the Phone Turned Off?
  • Hints
    • Android Emulators
    • Virtual Numbers for WhatsApp
    • How to use polls as buttons?
    • How to check who blocked you in Whatsapp?
    • Setting up a WhatsApp proxy
  • Integrations
    • Make.com
      • Ready-Made Scenarios
        • WhatsApp & Whisper API: Voice-to-Text Integration
        • Automated WhatsApp Group Message Forwarding in Make.com
      • Request Scenario Setup
    • Pabbly Connect
    • Google Contacts
    • DialogFlow
    • n8n
  • Tools
    • WhatsApp Number Checker
    • Automatic warm-up module
    • WhatsApp Activity Safety Meter
    • Residential Proxies from Whapi.Cloud
  • Troubleshooting
    • Couldn't Link Device โ€“ WhatsApp QR Code or Pairing Code Fails
    • Channel status โ€œSYNC_ERRORโ€
    • Not getting a READ status on webhook
    • 429 (Too Many Requests) - Soft Ban
    • โ€œWaiting for this message. This may take a whileโ€ โ€“ WhatsApp Message Error
    • Missing push notifications after connecting to API
  • Blocking
    • How to not get Banned?
    • How to do mailings without the risk of being blocked?
    • If My Number Is Banned, Can It Be Restored?
    • Unlocking Your WhatsApp Number
    • Connecting a New WhatsApp Number After a Ban: Steps and Recommendations
    • Warming Up New Phone Numbers for WhatsApp API
  • Partner Documentation
    • Introduction
    • Partner Dashboard Overview
    • Partner Program Guidelines
      • Workflow: Step-by-Step
      • Billing for Partners
      • Allocating Days to Customer Channels: Best Practices & Guide
      • Interface for channel management
    • Partner Documentation
      • Channel creation
      • Changing channel mode
      • Channel extension
      • Channel deletion
      • Getting the list of channels
      • Notices of end of days on balance
Powered by GitBook
On this page
  • Introduction
  • Preparations
  • Setting Up Your Webhook on Whapi.Cloud
  • Conclusion

Was this helpful?

  1. Receiving
  2. Webhooks
  3. Receive messages

Receive WhatsApp messages using Python

How to Receive WhatsApp messages using Python and webhook

PreviousReceive WhatsApp messages using Node jsNextHTTP API

Last updated 1 year ago

Was this helpful?

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

Preparations

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

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!

Detailed manual about webhooks

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 .

Whapi.Cloud Account: We'll use the Whapi.Cloud service to interface with WhatsApp. If you haven't already, .

here
official website
sign up here
https://github.com/Whapi-Cloud/python-whatsapp-chatbot
Settings
Webhook settings