How to Retrieve the Last History of WhatsApp Messages Using Python?

Estimated read time 3 min read

Retrieving the last history of WhatsApp messages programmatically is not straightforward using Python alone. WhatsApp does not provide a public API for accessing message history directly. However, you can use a third-party library called yowsup along with Python to interact with the WhatsApp service. Please note that using third-party libraries may have limitations and may not be officially supported by WhatsApp.

Here’s an example of how you can use the yowsup library to retrieve the last history of WhatsApp messages:

  1. Install the yowsup library by running the following command:
pip install yowsup2
  1. Import the required modules and define the necessary functions:
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.stanzaregulator import YowStanzaRegulator

from yowsup import env
from yowsup.common import YowConstants

class WhatsAppMessageReceiver:
    def __init__(self):
        self.messages = []

    def onEvent(self, event):
        if event.getName() == YowLayerEvent.RECEIVED_MESSAGE:
            message = event.getArg('message')
            self.messages.append(message)

def retrieve_whatsapp_messages(phone_number, password, target_phone_number, num_messages):
    # Create layers
    layers = (
        YowAuthenticationProtocolLayer,
        YowMessagesProtocolLayer,
        YowReceiptProtocolLayer,
        YowAckProtocolLayer,
        YowNetworkLayer
    )

    # Create WhatsApp connection parameters
    connection_params = {
        'phone': phone_number,
        'password': password,
        'timeout': 5,
        'message_history': True
    }

    # Initialize WhatsApp connection
    stack = YowStanzaRegulator.build(env.THE_ENVIRONMENT, layers)
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, connection_params)

    # Create the message receiver
    receiver = WhatsAppMessageReceiver()

    # Bind the receiver to the event layer
    stack.getLayer(YowMessagesProtocolLayer).addEventOccurredListener(receiver.onEvent)

    # Connect and login to WhatsApp
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))

    # Wait for the connection to be established
    while not stack.isReady():
        continue

    # Retrieve the last N messages
    stack.broadcastEvent(YowLayerEvent
  1. Use the retrieve_whatsapp_messages() function to retrieve the last num_messages messages from a WhatsApp conversation:
phone_number = 'your_phone_number'  # Your phone number with country code
password = 'your_password'  # Your WhatsApp password
target_phone_number = 'target_phone_number'  # Phone number of the WhatsApp conversation you want to retrieve messages from
num_messages = 10  # Number of messages to retrieve

messages = retrieve_whatsapp_messages(phone_number, password, target_phone_number, num_messages)
for message in messages:
    print(f"From: {message.getFrom(False)}")
    print(f"Message: {message.getBody()}")
    print(f"Timestamp: {message.getTimestamp()}")
    print()

Make sure to replace the placeholder values 'your_phone_number', 'your_password', and 'target_phone_number' with the appropriate values. Also, adjust the num_messages variable to specify the number of messages you want to retrieve.

Please note that the usage of yowsup may be subject to the terms and conditions set by WhatsApp. Make sure to review and comply with their guidelines to avoid any violations.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply