How to Automate WhatsApp Messages Using Python

Paulo Oliveira - Feb 23 - - Dev Community

Effective communication remains critical in the vast and intricate landscape of software development and testing. Whether sharing real-time test results, flagging discrepancies, or coordinating among distributed teams, fast and clear communication can often determine a project’s success and its downfall.

When it comes to popular communication and messaging platforms, WhatsApp is one of the world’s most popular platforms to send text and multimedia messages.

Talking about automated testing, Python comes with the ability to automate WhatsApp messages. By automating WhatsApp messages using Python, developers and testers can bridge communication gaps, automate notifications, and create a seamless flow of information.

The importance of such automation in test scenarios cannot be overstated. Traditional testing mechanisms, which often rely on manual notifications or require stakeholders to sift through extensive logs and reports, can lead to delays, missed anomalies, and, ultimately, costly errors.

By integrating WhatsApp messages into the test automation workflow, testers can instantly notify stakeholders of test results, critical bugs, or system failures. Such timely notifications can drastically reduce response times, making the testing process more agile, efficient, and effective.

In this Selenium Python tutorial, you will learn how to automate WhatsApp messages using Python libraries, taking some real-world scenarios.

Don’t waste your time manually converting decimal numbers to Roman numerals. Use our Decimal to Roman Converter tool to convert decimal numbers to Roman numerals and get results instantly.

Why is messaging automation important?

Messaging automation is the practice of sending messages, such as SMS, emails, or app-based chats, without any human involvement. This is accomplished by utilizing software, scripts, or tools that can be programmed to send messages in response to certain triggers, schedules, or events. The journey of messaging automation has come a long way from simple email auto-responders to the advanced chatbots we have today. It’s truly fascinating how it has evolved.

At its core, the objective of messaging automation is two-fold:

  • **Efficiency: **Eliminate the need for humans to repeatedly send standard messages, thus freeing up time and resources.

  • **Effectiveness: **Ensure that messages are delivered promptly and accurately, reducing the potential for human error.

In businesses, automation plays a crucial role in customer service, alerts, and notifications. For instance, when you sign up for a new online service, you automatically receive a verification email. This immediate response is the result of messaging automation.

Automating WhatsApp messages holds significant relevance in the test automation domain. With WhatsApp’s extensive user base and multifaceted usage, automation offers several benefits.

  • Enables scalability, making it practical for reaching large audiences efficiently.

  • Ensures timely delivery, which is crucial for time-sensitive messages.

  • Guarantees consistency in message content and tone, eliminating variations that manual messaging may introduce.

In the context of test automation, these advantages are invaluable for managing test notifications, integrating WhatsApp automation into CI/CD pipelines, and automating feedback collection after test phases.

Real-time notifications enable testers and developers to receive immediate alerts about test outcomes, facilitating faster issue resolution. Integration with CI/CD pipelines ensures stakeholders are notified at various development stages, from code integration to deployment. Automated WhatsApp surveys enable quick feedback collection post-testing, which is vital for agile development. Moreover, concise WhatsApp messages can efficiently convey test log highlights or anomalies.

Additionally, WhatsApp is a collaboration tool in distributed teams, ensuring seamless communication among stakeholders, regardless of location. Automating WhatsApp messages is a strategic tool that enhances efficiency, user experience, and the effectiveness of test automation.

Accurately count the number of words in your text with our easy-to-use word count tool. Perfect for meeting word count requirements. Try it out now for free!

Why Python and Selenium to automate WhatsApp messages?

Python and Selenium are excellent choices for automating WhatsApp messages as they possess a range of benefits, including versatility, user-friendliness, and strong capabilities.

Python, a widely embraced programming language, provides an extensive library collection that enhances its adaptability for automation purposes. Its straightforward and easily understandable syntax enables testers to create and run scripts for different automation scenarios swiftly.

Selenium is a powerful automation testing framework that seamlessly integrates with Python. It offers a variety of functionalities for interacting with web elements, making it perfect for automating interactions with the WhatsApp web interface. Selenium’s ability to work across various web browsers ensures that your automation scripts maintain consistency and reliability while you automate WhatsApp messages using Python.

Python and Selenium offer several advantages in automating WhatsApp messages across different operating systems. One key advantage is their platform-independence feature. This means that regardless of which operating system you are using, Python and Selenium allow you to automate WhatsApp messages seamlessly.

Whether you’re automating test notifications, integrating WhatsApp into your CI/CD pipelines, or collecting feedback, you get the robustness and flexibility needed to automate WhatsApp messages using Python and Selenium effectively.

Automating WhatsApp messages using Python and Selenium

Automating WhatsApp messages using Python and Selenium offers a compelling solution for streamlining communication processes. This dynamic pairing empowers users to interact with the web version of WhatsApp efficiently.

In this section, we will automate WhatsApp messages using Python and Selenium on WhatsApp Web. Our environment for this endeavor is a local Windows 11 machine.

You will be guided through the easy sending of a message, demonstrating how Python and Selenium can seamlessly interact with WhatsApp’s web interface, making automation a breeze.

So, let’s start!

Need to extract text from HTML code? Our free online tool makes it easy and fast. Save time by extracting only the text you need from HTML code in no time.

Setup

To automate WhatsApp messages using Python, we need an active WhatsApp account before starting our code. To have this, you can follow the below steps:

  1. **Active Phone Number: **Ensure you possess a phone number capable of receiving SMS or calls. WhatsApp employs this for its initial verification process.

  2. **Install WhatsApp: **If it’s not already on your mobile device, download and install the WhatsApp application from your respective app store (Google Play Store for Android, Apple App Store for iOS).

  3. **Account Setup: **Launch the app, follow the on-screen instructions to input your phone number, and verify it. Post-verification, configure your profile by appending a name and profile picture.

  4. **WhatsApp Web: **Acquaint yourself with WhatsApp Web — a functionality allowing you to use WhatsApp on a desktop browser. Some Python automation techniques might leverage this feature. To access it, simply access web.whatsapp.com.

With these prerequisites in place, you’re set to automate WhatsApp messages using Python.

After an active WhatsApp account, you must install the Selenium library using the pip command.

pip install selenium
Enter fullscreen mode Exit fullscreen mode

*Extract text from JSON data with our powerful and easy-to-use online free tool. Get the data you need quickly and efficiently, no technical skills required

Implementation

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time


options = webdriver.ChromeOptions()
options.add_argument(r"user-data-dir=C:\Github\python-whatsapp-messages\whatsapp-web\data")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get('https://web.whatsapp.com')


time.sleep(20)


driver.find_element(By.XPATH, "//*[@title='Eu']").click()
message_field = driver.find_element(By.XPATH, "//div[@class='to2l77zo gfz4du6o ag5g9lrv bze30y65 kao4egtt']//p[@class='selectable-text copyable-text iq0m558w g0rxnol2']")
message_field.send_keys("Message to be sent!")
message_field.send_keys(Keys.ENTER)
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

The script begins by importing the necessary modules.

In the initial steps of our automation journey, we take the pivotal step of configuring the Chrome WebDriver.

When accessing WhatsApp Web, first, a QR code will be presented, and you need to use your mobile phone connected to your account to scan it. Every time you run your code, you will have this QR code to be scanned, and in this way, you will never have an automated way to send a WhatsApp message.

To handle this, you need to do a crucial configuration, which is the custom user data directory. By employing the argument options.add_argument(r”user-data-dir=C:\Github\python-whatsapp-messages\whatsapp-web\data”), we instruct the Chrome browser to utilize a designated directory (C:\Github\python-whatsapp-messages\whatsapp-web\data) for storing user-specific data like cookies and cache. This ensures that login information persists across sessions, a crucial element in seamless automation.

In other words, the first time you run the code, you will scan the QR code (you will see a sleep in the code to give you time to scan it), and then, the data folder will be filled with all your cookies and cache data. The next time you run the code, no QR code will be presented, and no more scans need to be done.

Another important thing to mention is that you cannot copy and paste this code to another account. Every time you need to run in another machine and another account, you must scan the QR code in the first execution; then, you will have it automated for future executions.

Furthermore, we implement experimental options to fine-tune the behavior of the Chrome instance. The addition of options.add_experimental_option(“excludeSwitches”, [“enable-automation”]) allows us to exclude specific switches or features, notably the “enable-automation” switch. This switch, when enabled, is often used to detect automated interactions. By excluding it, we signal Chrome not to treat this session as automated, eliminating potential roadblocks.

Additionally, we incorporate options.add_experimental_option(‘useAutomationExtension’, False), a directive that advises Chrome to refrain from using automation extensions. While useful in certain contexts, these extensions can sometimes interfere with seamless automation. By deactivating them, we create an environment optimized for smooth and uninterrupted interactions.

Get your CSS validated by our CSS Validator and eliminate syntax errors and other issues that could affect your website’s performance. Ensure your CSS code is error-free today!

I’ve encountered a peculiar challenge while automating WhatsApp messages using Python. Occasionally, WhatsApp would unexpectedly request that I rescan the QR code, even if it had been scanned before. This happened intermittently and could disrupt the otherwise smooth automation process.

However, I discovered that using the two above lines of code options.add_experimental_option(“excludeSwitches”, [“enable-automation”]) and options.add_experimental_option(‘useAutomationExtension’, False) solves this intermittent problem.

These lines effectively instructed Chrome to exclude specific switches and avoid using automation extensions. This highlighted how these lines of code can make a significant difference, ensuring uninterrupted WhatsApp interactions and a hassle-free automation experience.

A Chrome WebDriver is then instantiated with Chrome options (driver). It navigates to the specified WhatsApp Web URL, showing in a maximized browser window.

A strategic pause is inserted, allowing sufficient time for users to scan the QR code and authenticate their session. This step ensures a seamless connection between the automation script and the WhatsApp web interface. As mentioned before, this QR code scan should be done just in the first script execution, so some user-specific data like cookies and cache will be stored, bypassing this scan in the next script executions.

Next, we select a specific chat for interaction. In this instance, we’ve chosen the chat identified by ‘Eu’ (in Portuguese) or ‘Me’ (in English). This step demonstrates how Selenium locates elements based on their attributes, in this case, the ‘title’ *attribute. Once the element is found, the *click() method is called on it. This line locates and clicks on an element, likely representing the user’s chat or conversation in the WhatsApp Web interface.

You can use browser inspection tools to locate specific elements on a web page for automation. These tools allow you to inspect the page’s HTML structure and identify elements by their attributes, such as ID, Class, or XPath. By understanding the page’s structure and using inspect tools, you can precisely identify the elements you want to interact with using automation frameworks like Selenium, enabling you to automate various tasks effectively.

You just need to find the element and then click on it.

Moving forward, we locate the message input field. This is the area where we’ll compose our automated message. Using XPath, we pinpoint the precise element corresponding to this input field. Once located, we employ the *send_keys() *method in Selenium to simulate typing. This emulates a user interaction, effectively inputting our desired message into the field.

To execute the message send action, we simulate the ‘Enter’ key press using send_keys(Keys.ENTER). This is akin to a user hitting the ‘Enter’ key on their keyboard to dispatch the message.

You can run this code using the command below:

python sample.py.
Enter fullscreen mode Exit fullscreen mode

In the terminal, you will get the result below:

After this time, WhatsApp web is opened, and the message is sent.

Reinforcing that the first time this script is executed, it will ask you to scan the WhatsApp QR Code and log in to your account within the WhatsApp Web. At this moment, the data folder is populated with the cookies and cache of your session.

This will allow you to avoid scanning the QR code in each execution after the first.

Take care of the content of this data folder; do not commit this to your repository. Put this in your .gitignore to avoid sharing sensitive data in a public repository.

In conclusion, this code segment showcases the power of Python and Selenium in automating WhatsApp messages. It provides a view into the world of effortless interaction with WhatsApp Web, allowing for the automation of essential tasks, streamlining communication, and enhancing efficiency in your environment.

Protect your XML data with our online free XML Escape tool. Quickly escape your code and be assured from vulnerabilities with just a few clicks!

Python libraries to automate WhatsApp messages

With its extensive libraries and modules, Python provides a robust framework for automating interactions on such platforms. Let’s explore some essential Python libraries tailored to automate WhatsApp messages using Python.

Pywhatkit

Pywhatkit is a Python library designed to automate various tasks, including sending WhatsApp messages. Its simplicity and effectiveness have garnered popularity among developers.

Benefits:

  • Easy to use with a straightforward API

  • Allows scheduling of messages

  • Versatile, with functionalities beyond WhatsApp automation

Limitations:

  • Limited to basic WhatsApp features

  • Just prepare the message; do not send it

Installation and Setup

pip install pywhatkit
Enter fullscreen mode Exit fullscreen mode

To use it, ensure you are logged into WhatsApp Web.

Key Methods and Functionalities

  • sendwhatmsg(): Send a WhatsApp message to a specific contact at a particular time

  • sendwhats_image(): Send an image to a contact/group with a caption

  • sendwhatmsg_to_group(): Send a WhatsApp message to a group at a particular time

  • sendwhatmsg_to_group_instantly(): Send a WhatsApp message to a group instantly

Selenium WebDriver: Automate browser activities locally or remotely. Explore Selenium components, version 4, and its pivotal role in automated testing.

Example: Sending a WhatsApp message using Pywhatkit

import pywhatkit


# Send a WhatsApp Message to a Contact at 10:50 AM
pywhatkit.sendwhatmsg("+1234567890", "Hello! This message is automated using Pywhatkit.", 10, 50)
Enter fullscreen mode Exit fullscreen mode

The above code will send a message, “Hello! This message is automated using Pywhatkit.”, to contact the number “+1234567890”, at 10:50 AM.

Make sure to replace +1234567890 with the recipient’s number and adjust the time accordingly.

You can run this code using the command below:

python sample.py
Enter fullscreen mode Exit fullscreen mode

In the terminal, a message is shown informing how often WhatsApp will open and the message will be sent.

After this time, WhatsApp web is opened, and the message is ready to be manually sent.

Selenium WebdriverIO is Javascript based test automation framework built over nodeJs. Learn with this guide how to use webdriverIO to perform web automation testing.

Twilio API for WhatsApp

Twilio, a renowned player in the cloud communications sphere, provides an API explicitly tailored for WhatsApp. This integration makes it easy to automate sending a WhatsApp message because it is more simple to communicate between your automation code and WhatsApp.

Benefits:

  • Uniform and consistent API, regardless of the messaging platform.

  • Comprehensive documentation, active community, and official support ensure smoother development cycles.

  • Beyond simple messages, it supports media, webhooks, and rich messaging formats.

Limitations:

  • Twilio is a paid service, potentially unsuitable for small-scale projects.

  • Reliance on an intermediary between the application and WhatsApp could introduce latency and a point of failure.

Discover 57 top automation testing tools list in 2024 for powerful and efficient testing solutions.

Installation and Setup

Install the Twilio Python library:

pip install twilio
Enter fullscreen mode Exit fullscreen mode

After installation, sign up on Twilio to obtain your account_sid, auth_token, and a Twilio-enabled phone number.

Key Methods and Functionalities

  • messages.create(): Used to send text, media messages, or even documents.

  • messages.fetch(): Retrieve specific message details using its SID.

  • media.create(): Send media messages, including images, videos, etc.

  • messages.list(): List all messages sent/received.

How does it differ from direct Python libraries?

While Python libraries interface directly with WhatsApp or its web version, the Twilio API introduces an abstraction layer. The communication occurs between the developer’s application and Twilio, and Twilio subsequently communicates with WhatsApp. This level of abstraction brings along the benefits of standardization and added features but introduces an external dependency.

Example: Sending a WhatsApp message using Twilio API

from twilio.rest import Client


account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)


client.messages.create(
  from_='whatsapp:+19876543210',
  body='Hello! This message is automated using Twilio.',
  to='whatsapp:+1234567890'
)
Enter fullscreen mode Exit fullscreen mode

Ensure the placeholders are replaced with actual values.

You can run this code using the command below:

python sample.py
Enter fullscreen mode Exit fullscreen mode

In the terminal, nothing is shown after sending the message.

Then, you can see that the message was automatically sent.

Automation testing uses tools and scripts to automate software test case execution. Dive deep into our detailed blog to learn the types of automation testing, its benefits, best practices, and more.

Other Python libraries

While mainstream libraries like Twilio and Pywhatkit garner a lot of attention due to their comprehensive features and wide adoption, other lesser-known Python libraries and tools to automate WhatsApp messages using Python might be worth exploring:

yowsup

This Python library acts as a CLI client, offering a robust interface for WhatsApp. It has been around for a while and provides functionalities similar to the core of WhatsApp’s operations. Being Python-native, integration with other Python-based tools and scripts is straightforward.

WhatsAPIDriver

This is a Python client for the WhatsApp web API. It enables the automation of sending and receiving messages through the web version of WhatsApp. While not as feature-rich as other libraries, it offers a simple and direct interface to interact with WhatsApp messages.

WhatsAPI

This Python library facilitates the sending and receiving of WhatsApp messages. It also provides functionalities for group management and contact handling. It’s an open-source project, so developers can contribute and customize according to their needs.

When considering these lesser-known tools, evaluating their community support, checking how actively they’re maintained, and understanding the potential risks associated with third-party solutions are crucial. Given the proprietary nature of WhatsApp, libraries can sometimes become outdated if they’re not actively updated to accommodate changes in WhatsApp’s architecture and policies.

Selenium is an open-source suite of tools and libraries to automate web browsers. Delve into its architecture, benefits, and more through our detailed tutorial on what is automation testing Selenium.

Guidelines for choosing the right tool

Selecting the perfect tool or library to automate WhatsApp messages using Python is crucial to achieving your desired outcomes. Let’s explore how to approach this decision to ensure you get the most value and efficiency from your selected tool.

  • Functionality & Scope: Some libraries offer comprehensive features, while others focus on specific functions.

  • Flexibility & Integration: Consider how easily a tool can integrate into your existing system. While some have broad compatibility, niche libraries may present integration challenges.

  • Scalability: Ensure your chosen tool can handle your operations’ scale. Some are designed for vast message volumes daily.

  • Cost: Cost can decide, especially for smaller projects or startups. Some services may lead to expenses based on usage.

In terms of test automation, stability is paramount. Not sending the expected message can lead to wrong interpretation. Furthermore, when it comes to updates and support, libraries with active communities are advantageous. They tend to have regular updates, bug fixes, and a support platform. Frequent official updates indicate active maintenance, reducing the risk of using outdated software. Extensive and clear documentation is a sign of a well-maintained tool.

Additionally, consider the risk of tools becoming deprecated due to newer alternatives or violations of WhatsApp’s terms.

When choosing a tool to automate WhatsApp messages using Python, assess the technical specifications, features, and project requirements. Ensure scalability for future growth so your solution doesn’t become a bottleneck. In this way, you can make a good choice.

In this blog on the mobile automation testing tools, we list the best 11 mobile automation testing tools with their advantages and business-friendly features.

Real-world scenarios in test automation

Let’s delve into real-world scenarios where automating WhatsApp messages using Python can enhance test automation processes.

Test notification via WhatsApp

Test automation scripts and suites run periodically or continuously in many software development environments. A notification system ensures that stakeholders are promptly informed about test results, whether successes or failures.

Benefits

Utilizing WhatsApp for test automation brings several advantages to the table. First and foremost, it offers immediate feedback, ensuring that developers and testers are promptly notified as soon as a test is completed, enabling them to take swift action.

Additionally, WhatsApp messages tend to be more engaging than traditional emails, reducing the risk of critical information being overlooked in crowded inboxes.

Implementation

Implementing test notifications through WhatsApp involves a simple process. After completing your test script, add a condition to assess the test’s outcome. Depending on whether the test passes or fails, craft an appropriate message indicating the success or failure.

Finally, send the tailored message to the designated recipient or group. This systematic approach ensures that test results are efficiently communicated via WhatsApp, streamlining the notification process in test automation workflows.

Experience real-time Android device test online with our platform. Ensure compatibility and performance on real devices instantly. Start testing now!

Integrating WhatsApp automation in CI/CD pipelines

CI/CD is a critical component in modern DevOps and Agile best practices. By integrating WhatsApp notifications within CI/CD pipelines, teams can be immediately notified about build statuses, deployment successes, or critical failures.

Benefits

Adding WhatsApp notifications in CI/CD pipelines provides several advantages. It enables real-time monitoring of pipeline activities, eliminating the need for constant dashboard checks. Additionally, these instant notifications facilitate collaboration, prompting quick responses such as debugging failed builds and expediting issue resolution. Beyond build statuses,

WhatsApp can also alert teams about critical events, including system warnings and completed deployments, showcasing its versatility as a communication tool in the CI/CD environment.

Implementation

Integrating WhatsApp into your CI/CD pipeline involves several steps. First, identify key stages where real-time notifications would provide value. Next, integrate WhatsApp automation tools with your CI/CD platforms like Jenkins or GitLab CI.

Finally, establish conditions and triggers to determine when WhatsApp messages should be sent. For instance, you can set up notifications to alert the developer team immediately in case of a deployment failure in the staging environment due to test failures. This implementation allows efficient and timely communication within your CI/CD process.

Demo: Automating WhatsApp messages using Python

In this section, we will implement an automatic way to send test notifications using WhatsApp messages using Twilio and LambdaTest Capabilities.

LambdaTest is an AI-powered test execution and orchestration platform that empowers developers and testers to perform Python automation testing seamlessly on over 3000+ real browsers and operating system combinations.

To perform Selenium Python testing on the LambdaTest cloud grid, you should use the capabilities to configure the environment where the test will run. In this blog, we will run the tests in Windows 11 and Chrome.

Test your native app and website on real iOS and test android app on real device cloud. LambdaTest is a convenient, cost-effective and centralised solution for running realtime and Automated test on real device cloud.

Test Scenarios

We will automate the below test scenarios:

Test Scenario 1 — Test Passed

Steps:

  1. Open the Simple Form Demo page in the LambdaTest Playground.

  2. Fill in the first field with the message “Message1”.

  3. Click the Get Checked Value button.

  4. Check that “Message1” is shown to the user on the right side.

  5. Send a test notification by WhatsApp with the test result.

Test Scenario 2 — Test Failed

Steps:

  1. Open the Simple Form Demo page in the LambdaTest Playground.

  2. Fill in the first field with the message “Message1”.

  3. Click the Get Checked Value button.

  4. Fill in the first field with the message “Message2”.

  5. Click the Get Checked Value button.

  6. Check that “Message1” is shown to the user on the right side.

  7. Send a test notification by WhatsApp with the test result.

Setting Up the Environment

Step 1: Install Selenium, pytest, and other necessary libraries

Once Python is installed, use the Python package manager, pip, to install Selenium, pytest, and Twilio just running the following command:

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Requirements.txt contains the dependencies that we want to install.

After running, you can see the below output:

Step 2: Download and Install Visual Studio Code or your preferred IDE

Step 3: Configure pytest in Visual Studio Code

To finish the configuration, we need to say to Visual Studio Code that pytest will be our test runner, so you can do this following the below instructions:

  1. Create a folder for your project (in our example, python-screenshots).

  2. Open the project folder in Visual Studio Code.

  3. Open the command palette (menu View > Command Palette), and type “Configure Tests”.

  4. Select pytest as the test framework.

  5. Select the root directory option.

You must also prepare the LambdaTest capabilities code to be inserted in our test script.

You can generate the capabilities code from the LambdaTest Capabilities Generator.

Then, you should get the “Username” and “Access Token” from the LambdaTest Password & Security section and set them as environment variables.

Test your native app and website on real iOS and Android devices cloud. LambdaTest is a convenient, cost-effective and centralised solution for running realtime and Automated test on real device cloud.

Demonstration

First of all, let’s create the project structure:

Implementation

[WEBSITE]
url = https://www.lambdatest.com/selenium-playground/simple-form-demo


[LOGIN]
username = your-lambdatest-username
access_key = your-lambdatest-access-key


[CLOUDGRID]
grid_url = hub.lambdatest.com/wd/hub
build_name = Python WhatsApp Message Build
test_name = Test Case X
w3c = True
browser_version = latest
selenium_version = 4.13.0


[ENV]
platform = Windows 11
browser_name = Chrome


[WHATSAPP]
account_sid = your-twilio-account-sid
auth_token = your-twilio-auth-token
my_twilio_phone_number = your-twilio-phone-number
notification_phone_number = phone-number-to-send-message

from twilio.rest import Client
import configparser


# Load the configuration file
config = configparser.ConfigParser()
config.read('config/config.ini')


def send_whatsapp_message(test_name, result):
    account_sid = config.get('WHATSAPP', 'account_sid')
    auth_token = config.get('WHATSAPP', 'auth_token')
    notification_phone_number = config.get('WHATSAPP', 'notification_phone_number')
    my_twilio_phone_number = config.get('WHATSAPP', 'my_twilio_phone_number')


    client = Client(account_sid, auth_token)


    if result == False:
        content = f'{test_name} - FAILED'
    else:
        content = f'{test_name} - PASSED'


    client.messages.create(
        from_='whatsapp:' + my_twilio_phone_number,
        body=content,
        to='whatsapp:' + notification_phone_number
    )

from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
import os
import configparser
from config import message


# Load the configuration file
config = configparser.ConfigParser()
config.read('config/config.ini')


@pytest.fixture()
def driver(request):
    username = os.getenv("LT_USERNAME")
    accessKey = os.getenv("LT_ACCESS_KEY")


    gridUrl = config.get('CLOUDGRID', 'grid_url')


    web_driver = webdriver.ChromeOptions()
    platform = config.get('ENV', 'platform')
    browser_name = config.get('ENV', 'browser_name')


    lt_options = {
        "user": config.get('LOGIN', 'username'),
        "accessKey": config.get('LOGIN', 'access_key'),
        "build": config.get('CLOUDGRID', 'build_name'),
        "name": config.get('CLOUDGRID', 'test_name'),
        "platformName": platform,
        "w3c": config.get('CLOUDGRID', 'w3c'),
        "browserName": browser_name,
        "browserVersion": config.get('CLOUDGRID', 'browser_version'),
        "selenium_version": config.get('CLOUDGRID', 'selenium_version'),
        "visual": True
    }


    options = web_driver
    options.set_capability('LT:Options', lt_options)


    url = f"https://{username}:{accessKey}@{gridUrl}"

    driver = webdriver.Remote(
        command_executor=url,
        options=options
    )


    yield driver

    driver.quit


def test_1(driver):
    driver.get(config.get('WEBSITE', 'url'))

    # Find an input element by its ID and enter text
    input_element = driver.find_element(By.ID, "user-message")
    input_element.send_keys("Message1")


    # Find an element by its ID and click on it
    element = driver.find_element(By.ID, "showInput")
    element.click()


    # Find an element by its ID and extract its text
    element = driver.find_element(By.ID, "message")


    result = element.text == "Message1"

    message.send_whatsapp_message("test_1", result)


def test_2(driver):
    driver.get(config.get('WEBSITE', 'url'))

    # Find an input element by its ID and enter text
    input_element = driver.find_element(By.ID, "user-message")
    input_element.send_keys("Message1")


    # Find an element by its ID and click on it
    element = driver.find_element(By.ID, "showInput")
    element.click()


    # Enter new text
    input_element.send_keys("Message2")


    # Click on the button again
    element.click()


    # Find an element by its ID and extract its text
    element = driver.find_element(By.ID, "message")


    result = element.text == "Message1"


    message.send_whatsapp_message("test_2", result)
Enter fullscreen mode Exit fullscreen mode

Test native, hybrid, and web apps on any mobile OS with our free Android emulator online. Sign up to optimize app performance.

Code Walkthrough

config.ini

This configuration file contains various sections, each with specific parameters.

[WEBSITE]: This section defines the URL where the Selenium tests will be conducted. In this case, it’s set to a demo page on LambdaTest (https://www.lambdatest.com/selenium-playground/simple-form-demo).

[LOGIN]: Here, the username and access_key are specified for personalized access to LambdaTest features. These credentials act as the platform’s gatekeeper.

[CLOUDGRID]: This section contains parameters related to parallel testing using the LambdaTest cloud grid. It includes the grid_url for the hub, build_name for organizing tests, test_name for identifying the specific test case, and versions of browser_version and selenium_version for compatibility. The w3c parameter adheres to global WebDriver standards.

[ENV]: This section defines the test environment, specifying the platform (Windows 11) and browser_name (Chrome) to mimic potential end-user conditions.

[WHATSAPP]: Contains Twilio account details, including account_sid, auth_token, my_twilio_phone_number, and notification_phone_number. These are used for sending automated WhatsApp messages using Python.

message.py

This script sends automated WhatsApp messages using Python based on test results.

The Twilio client is imported using twilio.rest import Client. The *configparser *module is used to read the configuration file (config.ini).

A function send_whatsapp_message is defined. This function takes test_name and result as arguments. test_name represents the name of the test case, and the *result *indicates whether the test passed or failed.

Inside the function, Twilio account details (account SID, authentication token, and phone numbers) are retrieved from the configuration file. Also, the Twilio client is instantiated using the account SID and authentication token.

Message content is defined depending on the test result (indicating whether the test passed or failed).

Finally, a WhatsApp message is sent using the Twilio client, specifying the sender’s number (my_twilio_phone_number), the content, and the recipient’s number (notification_phone_number).

You can test your test ipad app on device using official iOS Simulators for app testing.

test_simple_form_demo.py

This script contains the Selenium test cases.

The script begins by importing the necessary modules.

Similar to message.py, the configparser module is used to read the configuration file (config.ini).

A fixture driver is defined using pytest.fixture(). This pytest fixture sets up the Selenium WebDriver.

Initially, it fetches username and access key values from environment variables. These credentials are used for personalized access to LambdaTest. Also, the URL for the cloud grid where testing will occur (gridUrl) is retrieved.

You can learn more about the pytest fixtures from the video below:

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around Playwright, Cypress, and Selenium testing.

A Chrome WebDriver is then instantiated with ChromeOptions (web_driver). Also, platform *and *browser_name information is obtained from the config.ini file.

A dictionary lt_options is populated with all these test settings, including login credentials, build and test names, platform information, and browser details; most came from the configuration file. Finally, these options are set as capabilities for the WebDriver *instance using the *set_capability method. This ensures that the WebDriver is fully configured according to the parameters defined in the config file and the environment variables.

With the WebDriver set up, the fixture connects to the LambdaTest Selenium Grid, which allows running tests on cloud-hosted browsers. It then yields the driver, making it available to the test function, and closes it once the test is done.

The test cases (test_1 and test_2) use the Selenium WebDriver to interact with a sample form on the LambdaTest demo page.

Firstly, it navigates the Selenium WebDriver to a specific URL, in this case, the LambdaTest demo page.

Then, it locates an input field on the page and enters the text “Message1”.

Following that, it finds and clicks a button or trigger element.

After this interaction, it locates another element which likely contains the message sent as an output.

The test then compares the text content of this element with the expected value, “Message1”. The result of this comparison (True or False) is stored.

Finally, the test outcome is communicated through a WhatsApp message; the send_whatsapp_message function from message.py is called to send the WhatsApp message reporting whether the test passed or failed.

Test test_2 has almost the same content as test_1. However, there is a slight difference: after sending “Message1,” it sends “Message2” again.

Also, another change is in the comparison; the element.text is not compared to the correct message “Message2” but with “Message1”. The code is like this just to intentionally provoke a failure.

You can run the tests just with the below command.

pytest
Enter fullscreen mode Exit fullscreen mode

After running the test, you will get the following result in the terminal:

To pytest, the tests passed because we don’t have any assertions inside the tests. However, the correct test results are sent by the WhatsApp messages.

Upload your app on LambdaTest and test ios app without device for iOS application testing. Make the most of iOS app testing with official iOS simulators or real iPhones, and iPads on LambdaTest. Run Manual and Automated iOS app tests from anywhere in the world.

Best practices for automating WhatsApp messages

When harnessed correctly, automation can yield tremendous efficiencies, and automating WhatsApp messages is no exception. But like all powers, it comes with its responsibilities.

Below, we’ll delve into the best practices one should uphold to ensure the smooth and ethical deployment of automated WhatsApp messaging.

Being Aware of WhatsApp’s Terms and Conditions

Before diving headfirst into automation, understanding WhatsApp’s terms and conditions is paramount. Non-compliance can result in temporary or permanent bans and legal repercussions, especially for businesses. It’s essential to regularly review WhatsApp’s official policy page and consider joining developer communities for insights and interpretations while avoiding misuse.

Ensuring User Privacy and Data Security

WhatsApp conversations often contain sensitive and private information. Ensuring data protection isn’t just an ethical obligation but also a legal requirement in many regions. Trust and legal compliance are crucial, so always seek explicit consent before automating any message and limit data storage. Moreover, ensure that messages remain encrypted and conduct periodic security audits.

Handling Errors and Exceptions

In the world of automation, things don’t always go as planned. Exception handling in Selenium Python ensures your automation runs reliably without manual intervention. It also contributes to providing the right message to users, preventing confusion or misinformation. Anticipate common errors, maintain detailed logs, establish a feedback loop, and implement fallback mechanisms for critical notifications.

Scheduling and Avoiding Spam Behavior

Automated doesn’t mean incessant. Properly timed messages are more engaging and prevent fatigue or annoyance. Effective scheduling involves understanding your audience’s preferences and time zones. Avoid sending messages late at night or too early in the morning, implement rate limiting, and allow users an easy way to opt out of notifications.

Rate Limits and Potential Bans

The very nature of automation means tasks can be executed rapidly, potentially triggering rate limits or bans from platforms like WhatsApp. Gradually increase message frequency, monitor feedback to avoid spam reports, and ensure your content remains relevant.

Evolving Nature of WhatsApp’s Policies

WhatsApp frequently updates its policies, especially those related to automation and business use. Stay informed about policy changes and adjust your automation strategy to prevent penalties.

Maintenance and Updating of Libraries

When using third-party Python libraries to automate WhatsApp messages using Python, ensure they are regularly updated to support new features, fix bugs, and comply with WhatsApp’s policies. Set up alerts or regularly check for library updates, have a backup plan, and consider contributing to open-source libraries for community support.

While automating WhatsApp messages using Python holds tremendous potential, one must tread carefully. Respect for the platform’s guidelines, user privacy, and a genuine intent to provide value rather than spam is foundational to successful and ethical automation. By following these best practices, you protect your users and reputation and ensure the longevity and efficacy of your automation endeavors.

Conclusion

Merging the capabilities of WhatsApp, a dominant communication tool with the flexibility of Python, creates a potent platform, especially crucial in test automation.

This streamlines communication and redefines the feedback loops and notification systems within testing cycles, making them more immediate and actionable. As AI and machine learning innovations enhance chat functionalities, the potential for real-time testing insights via WhatsApp grows significantly.

Yet, as we embrace these advancements, ethical deployment remains paramount. Prioritizing user privacy, adhering to platform norms, and ensuring non-intrusive communications are essential. In this evolving landscape, those in test automation must balance the promise of WhatsApp and Python with a commitment to integrity and best practices.

Frequently Asked Questions (FAQs)

Can I automate WhatsApp messages using Python?

Automating WhatsApp messages using Python is possible, but it’s important to note that WhatsApp does not officially provide a public API for automation due to privacy and security concerns. However, some Python libraries can be used for web automation, including interacting with WhatsApp Web

What is API in WhatsApp?

The WhatsApp Business API is a backend mechanism that enables businesses to manage and automate their conversations on WhatsApp efficiently. Unlike a physical app or interface used on personal devices, the API seamlessly integrates into existing messaging platforms or systems businesses utilize.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .